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

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // atoll

/*
    Find the smallest number greater than n using the same digits.
    Returns -1 if no such number exists.

    Steps:
    1. Convert number to array of digits (as chars).
    2. Scan from right to left to find the pivot (first digit smaller than the next).
    3. If no pivot exists → digits are in descending order → no larger number.
    4. Find the smallest digit to the right of pivot that is larger than pivot.
    5. Swap them.
    6. Reverse the suffix to get the smallest possible number.
*/
long long nextGreaterNumber(long long n) {
    char buffer[32];
    sprintf(buffer, "%lld", n);

    int len = strlen(buffer);

    // Step 1: Find pivot
    int i;
    for (i = len - 2; i >= 0; i--) {
        if (buffer[i] < buffer[i + 1]) {
            break;
        }
    }

    // No pivot → no larger number
    if (i < 0) {
        return -1;
    }

    // Step 2: Find smallest digit greater than pivot to the right
    int j;
    for (j = len - 1; j > i; j--) {
        if (buffer[j] > buffer[i]) {
            break;
        }
    }

    // Step 3: Swap pivot with found digit
    char temp = buffer[i];
    buffer[i] = buffer[j];
    buffer[j] = temp;

    // Step 4: Reverse the suffix (i+1 to end)
    int left = i + 1;
    int right = len - 1;
    while (left < right) {
        char t = buffer[left];
        buffer[left] = buffer[right];
        buffer[right] = t;
        left++;
        right--;
    }

    // Convert back to number
    return atoll(buffer);
}

int main() {
    printf("Result: %lld\n", nextGreaterNumber(534965));  // 535469
    printf("-----------------------------\n");
    printf("Result: %lld\n", nextGreaterNumber(111));     // -1 (all digits identical)
    printf("-----------------------------\n");
    printf("Result: %lld\n", nextGreaterNumber(7600));    // -1 (already the largest)
}



/*
run:

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

*/

 



answered Mar 25 by avibootz
edited Mar 25 by avibootz

Related questions

...