Given a Integer, find the maximum number that can be formed from the digits. Input : 8754365 output : 8765543
Below is my solution:
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 >= 0; i--) {
for (int j = 0; j < times[i]; j++) {
largestNumber += i;
}
}
return Integer.parseInt(largestNumber);
}
Is there any optimization or anything weI can improve here?
Given a Integer, find the maximum number that can be formed from the digits. Input : 8754365 output : 8765543
Below is my solution:
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 >= 0; i--) {
for (int j = 0; j < times[i]; j++) {
largestNumber += i;
}
}
return Integer.parseInt(largestNumber);
}
Is there any optimization or anything we can improve here?
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 >= 0; i--) {
for (int j = 0; j < times[i]; j++) {
largestNumber += i;
}
}
return Integer.parseInt(largestNumber);
}
Is there any optimization or anything I can improve here?