Say you have an array of positive integers, manipulate them so that the concatenation of the integers of the resultant array is the largest number possible. Ex: {9,1,95,17,5}, result: 9955171
to compare
String strNumbers[] = new String[numbers.length];
for(int i = 0; i < numbers.length; ++i) {
strNumbers[i] = String.valueOf(numbers[i]);
}
Arrays.sort(strNumbers, new NumericComparator());
for(int i = 0; i < numbers.length; ++i)
System.out.print(strNumbers[i]);
System.out.print("\n");
}
class NumericComparator implements Comparator<String>{
public int compare(String num1, String num2) {
String str1 = num1 + num2;
String str2 = num2 + num1;
return str2.compareTo(str1);
}
}
Read full article from algorithm - How can I manipulate an array to make the largest number? - Stack Overflow
to compare
56
and 5
, we'd do a regular lexicographic comparison of 565
to 556
. Since 565
> 556
, we'll say that 56
is "bigger" than 5
, and should come first.int main() {
std::vector<std::string> v = {
"95", "96", "9", "54", "56", "5", "55", "556", "554", "1", "2", "3"
};
std::sort(v.begin(), v.end(),
[](const std::string &lhs, const std::string &rhs) {
// reverse the order of comparison to sort in descending order,
// otherwise we'll get the "big" numbers at the end of the vector
return rhs+lhs < lhs+rhs;
});
for (size_t i = 0; i < v.size(); ++i) {
std::cout << v[i] << ' ';
}
}
void PrintMinNumber(int numbers[]) {String strNumbers[] = new String[numbers.length];
for(int i = 0; i < numbers.length; ++i) {
strNumbers[i] = String.valueOf(numbers[i]);
}
Arrays.sort(strNumbers, new NumericComparator());
for(int i = 0; i < numbers.length; ++i)
System.out.print(strNumbers[i]);
System.out.print("\n");
}
class NumericComparator implements Comparator<String>{
public int compare(String num1, String num2) {
String str1 = num1 + num2;
String str2 = num2 + num1;
return str2.compareTo(str1);
}
}
Read full article from algorithm - How can I manipulate an array to make the largest number? - Stack Overflow