Body:
I am trying to solve the “A Very Big Sum” problem on HackerRank using Java.
The task is to sum large integers (long values), but my output is not matching the expected answer.
Here is my code:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long sum = 0;
for (int i = 0; i < n; i++) {
long val = sc.nextLong();
sum += val;
}
System.out.println(sum);
}
}
What I expected:
The code should correctly sum all the long values and print the total.
What is happening instead:
Even though I’m using long, the output for some test cases is still incorrect (either overflow-like wrong values or mismatched totals).
What I tried:
Printing each value to confirm input
Replacing
int nwithlong nChecking loop logic
Running sample test cases manually
My question:
Why is my solution giving incorrect results for some test cases, even though I’m using long?
Is there something wrong with how I’m reading input or summing the values?