Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

2 numbers a and b find the smallest number greater than b by interchanging the digits of a

+1 vote
asked Jun 29, 2019 by anonymous

1 Answer

0 votes
answered Nov 16, 2025 by PinHao (140 points)
for c++:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <limits> // For numeric_limits

int findSmallestGreaterPermutation(int a, int b) {
    std::string s = std::to_string(a);
    std::sort(s.begin(), s.end()); // Sort to get the smallest permutation first for next_permutation

    long long smallest_greater_num = std::numeric_limits<long long>::max();
    bool found = false;

    do {
        long long current_num = std::stoll(s); // Convert string to long long

        if (current_num > b) {
            found = true;
            if (current_num < smallest_greater_num) {
                smallest_greater_num = current_num;
            }
        }
    } while (std::next_permutation(s.begin(), s.end()));

    if (found) {
        return static_cast<int>(smallest_greater_num); // Cast back to int if within range
    } else {
        return -1;
    }
}

int main() {
    int a, b;
    std::cout << "Enter two numbers (a and b): ";
    std::cin >> a >> b;

    int result = findSmallestGreaterPermutation(a, b);

    if (result != -1) {
        std::cout << "Smallest number greater than " << b << " by interchanging digits of " << a << " is: " << result << std::endl;
    } else {
        std::cout << "No such number found." << std::endl;
    }

    return 0;
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...