-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathLargeSum.java
More file actions
49 lines (42 loc) · 1.58 KB
/
LargeSum.java
File metadata and controls
49 lines (42 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package problem13;
/*
Large sum
Problem 13
Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.
The numbers are stored in a file called "list.txt"
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class LargeSum{
public static void main(String[] args) throws FileNotFoundException{
File f = new File("src/problem13/list.txt"); // "list.txt" is the file with all the numbers
Scanner scan = new Scanner(f);
int[][] list = new int[100][50];
String[] s = new String[100]; // stores each line in the file
putIntoArray(s, list, scan);
int digitHolder = 0;
int[] remainderHolder = new int[50];
for (int i = 49; i >= 0; i--) { // i is the column
for (int j = 0; j < 100; j++) { // j is the row
digitHolder += list[j][i]; // numbers are added down column 'i'
}
remainderHolder[i] = digitHolder % 10; // the remainder
digitHolder /= 10; // the sum to be carried over
}
System.out.print(digitHolder);
for (int i = 0; i < 50; i++) {
System.out.print(remainderHolder[i]);
}
System.out.println();
}
public static void putIntoArray(String[] s, int[][] list, Scanner scan) {
for (int i = 0; i < s.length; i++) {
s[i] = scan.nextLine(); // scans each line from the file into s[]
for (int j = 0; j < s[i].length(); j++) {
String character = "" + s[i].charAt(j);
list[i][j] = Integer.parseInt(character);
}
}
}
}