I know that this is probably not the most efficient way to encode, but this is what I have so far, and it works until the numbers get really big. The code should read 2 numbers from the file, for example, "052" and "61". Then he must sort the first number from maximum to smallest to maximize the number, and the second number from smallest to maximum to make it as small as possible. (520 and 16) Then he prints the difference between them, in this case: 504.
Two of them: "3827367453723784675745843783623672348745389734268374687" and "1682761482512674172712635416571265716235471625176235741". Sorting the numbers from largest to smallest and least great works fine, but when I try to parse it into an integer a NumberFormatException. I understood, because the number was too large to be stored in int, so I tried parsing in Long, but this led to the same error.
I read the numbers as String, then made an array Stringstoring each number in a separate index. Then I created an array intwhere I pretty much had the same array, except for the integer form, instead String. Then I sorted the arrays int. Then I created another one Stringto store the new sorted numbers, then I tried to parse Stringwhere the exception was thrown.
Any suggestions?
import java.io.*;
import java.util.*;
import java.text.*;
import static java.lang.System.*;
public class BigDif
{
public static void main(String[] args) throws IOException
{
Scanner scan = new Scanner (new File ("BigDif.dat"));
int numRuns = scan.nextInt();
scan.nextLine();
for (int i = 0; i < numRuns; i++)
{
String firstNum = scan.nextLine();
String secondNum = scan.nextLine();
String[] firstNum2 = new String[firstNum.length()];
String[] secondNum2 = new String[secondNum.length()];
int[] firstNum3 = new int[firstNum.length()];
int[] secondNum3 = new int[secondNum.length()];
int big = 0;
int notBig = 0;
String firstNum4 = null;
String secondNum4 = null;
int firstNum5 = 0;
int secondNum5 = 0;
for (int j = 0; j < firstNum.length(); j++)
{
firstNum2[j] = Character.toString(firstNum.charAt(j));
}
for (int j = 0; j < secondNum.length(); j++)
{
secondNum2[j] = Character.toString(secondNum.charAt(j));
}
for (int j = 0; j < firstNum2.length; j++)
{
firstNum3[j] = Integer.parseInt(firstNum2[j]);
secondNum3[j] = Integer.parseInt(secondNum2[j]);
}
Arrays.sort(firstNum3);
Arrays.sort(secondNum3);
for (int m = 0; m < firstNum3.length; m++)
{
if (m == 0)
firstNum4 = (Integer.toString(firstNum3[m]));
else
firstNum4 = (Integer.toString(firstNum3[m]))+ firstNum4;
}
for (int m = 0; m < secondNum3.length; m++)
{
if (m == 0)
secondNum4 = (Integer.toString(secondNum3[m]));
else
secondNum4 += (Integer.toString(secondNum3[m]));
}
firstNum5 = Integer.parseInt(firstNum4);
secondNum5 = Integer.parseInt(secondNum4);
if (firstNum5 >= secondNum5)
{
big = firstNum5;
notBig = secondNum5;
}
else
{
big = secondNum5;
notBig = firstNum5;
}
out.println(big - notBig);
}
}
}
source
share