# Digits comparator(a1,a2,b1,b2,b3 < b1,b2,b3,a1,a2 ?) in Java

• compare(int a, int b) means
ie: a = 12345, b = 123;
a1 = 1, a2 = 2, a3 = 3, a4 = 4, a5 = 5;
b1 = 1, b2 = 2, b3 = 3;
compare the below two lists
list1: a1 a2 a3 a4 a5 b1 b2 b3
list2: b1 b2 b3 a1 a2 a3 a4 a5
===>
1 2 3 4 5 1 2 3
1 2 3 1 2 3 4 5
the edges are a5 -> b1 in the 1st list, and b3 -> a1 in the 2nd one
the loop is designed for running length(a) + length(b) times
while running at the edge, switch to another one.
a = b while running at b1 on list1;
b = a while running at a1 on list2;

for the digits manipulation, an int[2]{length, reversed} array is introduced

besides, be carefully to handle the number is 0. we assume 0 is the minimum one, so if 0 occurs, 0 < any others
a special case is the maximum num in the array is 0. it means min == max, all nums is the same; return "0";

``````public class Solution {
public String largestNumber(int[] nums) {
if (nums == null || nums.length == 0) return "";
Integer[] numObjs = new Integer[nums.length];
for (int i = 0; i < nums.length; i++)
numObjs[i] = nums[i];
Arrays.sort(numObjs, (a, b) -> {
if (a == b) return 0;
if (a == 0) return 1;
if (b == 0) return -1;
int[] revA = reverse(a), revB = reverse(b);
a = revA[1]; b = revB[1];
int diff = 0;
for (int i = 0; i < revA[0] + revB[0]; i++) {
if (i == revA[0]) a = revB[1];
if (i == revB[0]) b = revA[1];
diff = b % 10 - a % 10;
if (diff > 0) return 1;
else if (diff < 0) return -1;
a /= 10; b /= 10;
}
return 0;
});
if (numObjs[0] == 0) return "0";
StringBuilder largest = new StringBuilder();
for (int num : numObjs) largest.append(num);
return largest.toString();
}

private static int[] reverse(int num) {
int rev = 0, bitNum = 0;
while (num > 0) {
rev = rev * 10 + num % 10;
num /= 10;
bitNum++;
}
return new int[]{bitNum, rev};
}
}
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.