sorting digits of an intput

hey guys ..

I want to sort the digits of an input integers . Let's suppose that we have two Variables x , y ... the user will enter the value of x ( consider the user entered 234156) i want to set y to be 123456 .
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <string>
#include <iostream>
#include <algorithm>


int main()
{
    int x;
    std::cin >> x;
    std::string foo = std::to_string(x);
    std::sort(foo.begin(), foo.end());
    int y = std::stoi(foo);
    std::cout << y;
}
Last edited on
can we make it with a standard way without strings ?? using int only .
To apply a string (or sequence, does not mater) transformation to integer. Sure, you can:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include<iostream>
#include<cmath>


int ipow(int base, int exp)
{
    int result = 1;
    for(int i = 0; i < exp; ++i)
        result *= base;
    return result;
}

int get_digit(int num, int n)
{
    return (num / ipow(10, n)) % 10;
}

void set_digit(int& num, int n, int digit)
{
    num -= get_digit(num, n) * ipow(10, n);
    num += ipow(10, n) * digit;
}

int main()
{
    int x;
    std::cin >> x;
    int digits = std::log10(x) + 1;
    //Selection sort
    for(int i = 0; i < digits; ++i) {
        int max = -1;
        int max_index = -1;
        for (int j = i; j < digits; ++j)
            if (max < get_digit(x, j)) {
                max = get_digit(x, j);
                max_index = j;
            }
        set_digit(x, max_index, get_digit(x, i));
        set_digit(x, i, max);
    }
    std::cout << x;
}

Topic archived. No new replies allowed.