Problem
Arrange Given Numbers To Form The Biggest Number Possible.
OR
Write a function that takes a number as input and outputs the biggest number with the same set of digits.
Examples
Example 1:
Input: num = 423865
Output: 865432
Similar Problems
Next Greater Element 3 - Find smallest number larger than given number using same digits
Solution
Method 1 - Sorting
This problem is similar to Largest Number From Given Numbers. But this is easier, as we don’t have to take care of array of numbers, which can have more than 1 digit numbers.
In order to get the biggest number by rearranging the digits, all we need is to order all digits in descending order. For example, if the input is 62832, we just need to sort them and output 86322.
To start with, we need 3 basic methods here:
- Convert number to a list of digits
- Sort the digits in descending order
- Construct the number from the list of digits
Code
Java
public class BiggestNumber {
public static String biggestNumber(long number) {
StringBuilder digits = new StringBuilder();
while (number > 0) {
digits.insert(0, Long.toString(number % 10));
number /= 10;
}
char[] charArray = digits.toString().toCharArray();
Arrays.sort(charArray);
StringBuilder sortedDigits = new StringBuilder(new String(charArray));
if (sortedDigits.charAt(0) == '0') {
return "0";
}
return sortedDigits.toString();
}
}
Python
def biggest_number(number):
digits = number_to_digits(number)
digits.sort(reverse=True)
return digits_to_number(digits)
def number_to_digits(number):
digits=[]
while number:
digits.insert(0, number%10)
number = number/10
return digits
def digits_to_number(digits):
number = 0
base = 1
for d in reversed(digits):
number += d * base
base *= 10
return number