I'm a beginner in programming and I've been doing the Project Euler programming problems to practice, I've been able to make my way so far, but this time I had to ask for help. Without spoilers, the problem I'm trying to solve consists of finding the sum of the digits of a very large number, so I can't hold it in an int or a double. So I made this method to multiply two strings containing a numeric value.
private static String multiply(String a, String b) {
// No, I'm not checking if the strings are numeric
int subTotal = 1, extra = 0;
String waitingString = "";
StringBuilder number1 = new StringBuilder(a);
StringBuilder number2 = new StringBuilder(b);
List<String> numbers = new ArrayList<String>();
// The reason I reverse the numbers is the for() loops
// I don't want to count down through the numbers, that
// would just confuse me more.
number1.reverse();
number2.reverse();
for (int i = 0; i < number1.length(); i++) {
waitingString = "";
subTotal = Character.getNumericValue(number1.charAt(i));
for (int j = 0; j < number2.length(); j++) {
subTotal *= Character.getNumericValue(number2.charAt(j));
subTotal += extra;
char[] temp = String.valueOf(subTotal).toCharArray();
waitingString = temp[temp.length - 1] + waitingString;
if (subTotal >= 10 || ((j == number2.length() - 1) && (String.valueOf(subTotal).length() > 1))) {
extra = Integer.parseInt(String.valueOf(subTotal).substring(0, temp.length - 1));
} else {
extra = 0;
}
subTotal = Character.getNumericValue(number1.charAt(i));
}
for (int k = 0; k < i; k++) {
waitingString += "0";
}
waitingString = extra + "" + waitingString;
numbers.add(waitingString);
}
// sumAll() is not the problem just in case you were wondering.
// Because as you've read the code, I'm passing a List<String>
// to it and as I was trying to find the error I printed the list
// before everything to check the values and the error was already
// there, 3 of the values are wrong.
return sumAll(numbers);
}
When testing I'm multiplying this number by itself: 1125899906842624. The result should be 1267650600228229401496703205376. But I'm getting 1267650600228229401607703205376. That's a difference of 111000000000. I've been trying to find the error for 2 days and i just can't. I'm not looking for alternative or better ways to do this, I just can't find the error in my code that adds more than it should. If you need to see the rest of the code I can provide it and please don't mind spelling/grammar errors, english is not my native language.
BigIntegerclass? :)