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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
#include <iostream>
// split into digits ; abcd < 10'000 (four or less digits)
void split( unsigned int abcd, int& a, int& b, int& c, int& d )
{
d = abcd % 10 ;
c = abcd/10 % 10 ;
b = abcd/100 % 10 ;
a = abcd/1000 % 10 ;
}
// a, b, c, d in [0,9] (digits); combine to get integer abcd
unsigned int combine( int a, int b, int c, int d ) { return d + c*10 + b*100 + a*1000 ; }
// note: all overloads of sort sort in descending order
void sort( int& a, int& b ) { if( a < b ) { int temp = a ; a = b ; b = temp ; } }
void sort( int& a, int& b, int& c ) { sort(a,b) ; sort(b,c) ; sort(a,b) ; }
void sort( int& a, int& b, int& c, int& d ) { sort(a,b,c) ; sort(c,d) ; sort(a,b,c) ; }
// abcd < 10'000 (four or less digits) ; sort digits in descending order
unsigned int sort_digits( unsigned int abcd )
{
int a, b, c, d ;
split( abcd, a, b, c, d ) ;
sort( a, b, c, d ) ;
return combine( a, b, c, d ) ;
}
int num_digits( unsigned int n )
{
if( n < 10 ) return 1 ;
int ndigits = 0 ;
for( ; n != 0 ; n /= 10 ) ++ndigits ;
return ndigits ;
}
// trim to most significant ndigits
unsigned int trim( unsigned int n, int ndigits )
{
while( num_digits(n) > ndigits ) n /= 10 ;
return n ;
}
// n has four or less digits ; sort digits in descending order
unsigned int sort( unsigned int n )
{
n %= 10000 ; // abundant caution
return trim( sort_digits(n), num_digits(n) ) ;
}
int main()
{
for( unsigned int v : { 0, 1, 10, 17, 107, 170, 1070, 7010, 1007, 1700, 1722, 6366, 5555 } )
std::cout << v << ' ' << sort(v) << '\n' ;
}
|