Rearranging numbers to get the largest number Given a Integer, find the maximum number that can be formed from the digits.



Input: 8754365
Output: 8765543 




private static int largestNumber(int data) {
    int num = data;
    int[] times = new int[10];
    while (num != 0) {
        if (num == 0) {
            break;
        }
        int val = num % 10;
        times[val]++;
        num /= 10;
    }
    String largestNumber = "";
    for (int i = 9; i &gt;= 0; i--) {
        for (int j = 0; j &lt; times[i]; j++) {
            largestNumber += i;
        }
    }
    return Integer.parseInt(largestNumber);
}


Is there any optimization or anything I can improve here?
while (num != 0) {
    if (num == 0) {
        break;
    }



That if is redundant and can be removed.

Using a StringBuilder for largestNumber is roughly twice as fast on my machine.

Avoiding strings altogether is faster still:

int largestNumber = 0;
for (int i = 9; i &gt;= 0; i--) {
  for (int j = 0; j &lt; times[i]; j++) {
    largestNumber = largestNumber * 10 + i;
  }
}
return largestNumber;


You might want to return a long instead of an int so that, for example, largestNumber(Integer.MAX_VALUE) returns 8776444321, as expected.