Saturday, March 12, 2011

Project Euler - problem 13 solution (java)

I solved this problem using the classical hand-based calculation method. You start adding up all the numbers from the smallest digit, write down the smallest digit of the sum, and add the remaining digits while calculating the next digit.







import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class Test
{
public static void main(String[] args) throws FileNotFoundException
{
File file = new File("data.dat"); // This is the file where a hundred 50-digit numbers (distributed on each line) are located.
Scanner reader = new Scanner(file);

String[] numbers = new String[100];

for(int index = 0; index < numbers.length; index++) // Put each line of "data.dat" file into the "numbers" array.
{
numbers[index] = reader.nextLine();
}

String output = "";
int extraDigits = 0;

for(int digitIndex = numbers[0].length()-1; digitIndex >= 0; digitIndex--) // Decide the digit.
{
int sum = 0;
for(int index = 0; index < numbers.length; index++) // Look through each "numbers" element.
{
sum += Character.getNumericValue(numbers[index].charAt(digitIndex)); // Add selected digit of each element.
}
sum += extraDigits; // Add the previous digit calculation's leftover.
int firstDigit = sum % 10; // Get the first digit of the sum.
extraDigits = (sum - firstDigit) / 10; // Get the leftover to be added during the calculation of next digit.

if(digitIndex == 0) // If this was the last digit calculation,
output = sum + output; // Add the whole sum to the result.
else // Otherwise,
output = firstDigit + output; // Add only the first digit to the result.
}

System.out.println(output);
}
}



The result is the sum of all those hundred 50-digit numbers.

No comments:

Post a Comment