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}, r
My strategy is to use any sorting algorithm with a custom compare function.
Before we dive into the code, here are some things to consider:
If the number of digits are equal, then the comparison is straight forward. But if the number of digits are unequal, then we extract the leftmost digit of the integer with more number of digits (and then compare recursively).
Code explains best. So, here is my working code:
int numDigits(int number)
{
int digits = 0;
if (number < 0) digits = 1; // remove this line if '-' counts as a digit
while (number) {
number /= 10;
digits++;
}
return digits;
}
int comparator ( const void * elem1, const void * elem2 )
{
int x = *(int *)elem1;
int y = *(int *)elem2;
if(x==y) return 0;
int xLen = numDigits(x);
int yLen = numDigits(y);
if(xLen==yLen)
{
return x>y ? -1 : +1;
}
else
{
int xTens = pow((double)10,(double)xLen-1);
int yTens = pow((double)10,(double)yLen-1);
int xLeftmostDigit = (xTens != 0) ? x/xTens : 0;
int yLeftmostDigit = (yTens != 0) ? y/yTens : 0;
if( xLeftmostDigit == yLeftmostDigit )
{
if(xLen yLeftmostDigit ? -1 : +1;
}
}
return false;
}
I wrote the above function specifically to be used with the stl's qsort.
This is my test code:
int main(int argv,char **argc) {
//Ex: {9,1,95,17,5}, result: 9955171
int arr[] = {9,1,95,17,5};
int arrLen = 5;
for(int i=0; i