## Thursday, November 17, 2016

### Smallest number by rearranging digits of a given number - GeeksforGeeks

Smallest number by rearranging digits of a given number - GeeksforGeeks
Find the Smallest number (Not leading Zeros) which can be obtained by rearranging the digits of given number.

1. Count the frequency of each digit in the number.
2. Place the smallest digit (except 0) at the left most of required number.
and decrement the frequency of that digit by 1.
3. Place all remaining digits in ascending order from left to right.
`int` `smallest(``int` `num)`
`{`
`    ``// initialize frequency of each digit to Zero`
`    ``int` `freq[10] = {0};`

`    ``// count frequency of each digit in the number`
`    ``while` `(num)`
`    ``{`
`        ``int` `d = num % 10; ``// extract last digit`
`        ``freq[d]++; ``// increment counting`
`        ``num = num / 10; ``//remove last digit`
`    ``}`

`    ``// Set the LEFTMOST digit to minimum expect 0`
`    ``int` `result = 0;`
`    ``for` `(``int` `i = 1 ; i <= 9 ; i++)`
`    ``{`
`        ``if` `(freq[i])`
`        ``{`
`            ``result = i;`
`            ``freq[i]--;`
`            ``break``;`
`        ``}`
`    ``}`

`    ``// arrange all remaining digits`
`    ``// in ascending order`
`    ``for` `(``int` `i = 0 ; i <= 9 ; i++)`
`        ``while` `(freq[i]--)`
`            ``result = result * 10 + i;`

`    ``return` `result;`
`}`