Sorting digits of an integer

前端 未结 9 1277
日久生厌
日久生厌 2020-12-16 01:26

You are given an integer 51234 (say) we need to sort the digits of a number the output will be 12345.

How to do it without using array ?

9条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-16 02:01

    Divide by 10 given integer in loop. Print the reminder in each iteration.

    Or "sort" means what here? For real sorting you will need two loops. One of them will be from 0 to 9. Another one will be that was described early.

    int main()
    {
        int x = 0;
        cin >> x;
    
        for ( int l = 0; l < 10; ++l )
        {
            int rem = x % 10;
            int tx = x / 10;
            while ( rem || tx )
            {
                if ( rem == l ) cout << rem;
                rem = tx % 10;
                tx = tx / 10;
            }
        }
        cout << endl;
    }
    

提交回复
热议问题