TL;DR: See demo of below logic at IDEONE.
Pretend the number is an array of digits, e.g. named d[]
, and pretend that index 0
is the rightmost digit.
A bubblesort will move higher values to higher indexes, so if we keep that logic, sorting d
would result in the desired largestNumber
, e.g. 1357924
becomes 9754321
.
Assume you have a method pow10(n)
which calculates 10n, you can then get digit at any index:
d[i] = number / pow10(i) % 10
Example:
6 4 2 0 index
↓ ↓ ↓ ↓
number = 1357924
d[4] = 1357924 / pow10(4) % 10
= 1357924 / 10000 % 10
= 135 % 10
= 5
In a bubblesort, you swap adjacent elements if lower-indexed element is larger, so first we need the two values. Let's say we're doing it for i = 3
:
6 4 2 0 index
↓ ↓ ↓ ↓
number = 1357924
i = 3
a = d[i] = d[3] = 7
b = d[i+1] = d[4] = 5
Since a > b
we need to swap the values. We can do that as follows:
1357924
- 7000 Clear digit at i=3
- 50000 Clear digit at i=4
=1300924 Value with digits cleared
+ 70000 Set digit at i=4
+ 5000 Set digit at i=3
=1375924 Value with digits at index 3 and 4 swapped
The formula for that is:
number = number - a * pow10(i) - b * pow10(i+1)
+ a * pow10(i+1) + b * pow10(i)
Which can be refactored to:
number += ((a - b) * 10 - (a - b)) * pow10(i)
Now that you know how to get the "array element value", aka d[i]
, and how to "swap array elements" using the above formula, you write that into a normal bubblesort algorithm, so you can:
largestNumber = sortDigits(number)
You've now calculated the largest value. To calculate the smallest value, you need to simply reverse the digits, but before you do that, you need to ensure that d[0] != 0
:
n = largestNumber, i = 0
while (n % 10 == 0) { // locate least non-zero digit
n /= 10
i++
}
if (i != 0) {
// clear least digit and add at index 0
n = n / 10 * pow10(i + 1) + n % 10
}
Example:
n = 97500
After loop: n = 975, i = 2
n / 10 = 97
* pow10(i + 1) = 97000
+ n % 10 = 97005
Now you can calculate the other value you need:
smallestNumber = reverse(n)
See e.g. Java reverse an int value without using array for how to do that.