-5

Can anyone help me with a C++ code that prints out all the possible permutations of the given number.

For example, if the number N = 123, then {123, 132, 213, 231, 312, 321} are the possible permutations.

I have researched and could find the code only for string and not an integer.

Thanks.

4
  • 4
    convert int to string first and re-use code you've found Jan 10, 2019 at 2:05
  • It's no different. Jan 10, 2019 at 2:06
  • 1
    You don't have to convert string to integer. Make 'N' as string will be enough
    – gameon67
    Jan 10, 2019 at 2:27
  • I need to use the permutations for further calculations, so i guess I will have to convert them into integers again? Jan 11, 2019 at 3:07

1 Answer 1

4

You might use:

void display_permutation(std::size_t n)
{
    std::string s = std::to_string(n);
    std::sort(s.begin(), s.end());
    do {
        std::cout << s << std::endl;
    } while (std::next_permutation(s.begin(), s.end()));
}

Demo

3

Not the answer you're looking for? Browse other questions tagged or ask your own question.