How to find the smallest number greater than a given number, using the same digits in Pascal

1 Answer

0 votes
program NextGreaterNumber;

{
    Find the smallest number greater than N using the same digits.
    Returns -1 if no such number exists.

    Algorithm (same as next permutation):
    1. Convert number to array of characters (digits).
    2. Scan from right to left to find the pivot:
       the first digit that is smaller than the digit to its right.
    3. If no pivot exists → digits are in descending order → no larger number.
    4. Find the smallest digit to the right of the pivot that is larger than it.
    5. Swap pivot with that digit.
    6. Reverse the suffix (everything to the right of pivot).
}

function NextGreaterNumber(n: Int64): Int64;
var
    s: string;
    i, j, left, right: Integer;
    temp: Char;
begin
    Str(n, s);  { Convert number to string }

    { Step 1: Find pivot }
    i := Length(s) - 1;
    while (i >= 1) and (s[i] >= s[i + 1]) do
        Dec(i);

    if i < 1 then
    begin
        { No pivot → no larger permutation }
        NextGreaterNumber := -1;
        Exit;
    end;

    { Step 2: Find smallest digit greater than pivot to the right }
    j := Length(s);
    while (j > i) and (s[j] <= s[i]) do
        Dec(j);

    { Step 3: Swap pivot with found digit }
    temp := s[i];
    s[i] := s[j];
    s[j] := temp;

    { Step 4: Reverse the suffix (i+1 .. end) }
    left := i + 1;
    right := Length(s);
    while left < right do
    begin
        temp := s[left];
        s[left] := s[right];
        s[right] := temp;
        Inc(left);
        Dec(right);
    end;

    { Convert back to integer }
    Val(s, NextGreaterNumber);
end;

begin
    Writeln('Result: ', NextGreaterNumber(534965));  { 535469 }
    Writeln('-----------------------------');
    Writeln('Result: ', NextGreaterNumber(111));     { -1 (all digits identical) }
    Writeln('-----------------------------');
    Writeln('Result: ', NextGreaterNumber(7600));    { -1 (already the largest) }
end.



(*
run:

Result: 535469
-----------------------------
Result: -1
-----------------------------
Result: -1

*)

 



answered Mar 25 by avibootz

Related questions

...