Java program to add two huge numbers | Basic Java Programming Solutions | AskTheCode
Problem:
Given a series of integer pairs A and B, output the sum of A and B.
Input Format:
Each line contains two integers, A and B. One input file may contain several pairs P
where 0 <= P <= 12.
Output Format:
Output a single integer per line - The sum of A and B.
Constraints:
0 <= A, B <= 10^98
Sample Input:
1 2
2 5
10 14
Sample Output:
3
7
24
Discussion:
The Constraints tells us that it's not possible to use integers or long data types here, because the length of A and B can be 10^98, wiz. beyond the range of any of int, float, double and long.
So, we will store the input in Strings.
Code:
//imports for BufferedReader*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
class Solution{
public static void main(String args[] ) throws Exception {
/*BufferedReader*/
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = "";
while((input = br.readLine()) != null){
String val1 = input.split(" ", 0)[0];
String val2 = input.split(" ", 0)[1];
BigInteger a = new BigInteger(val1);
BigInteger b = new BigInteger(val2);
BigInteger res = a.add(b);
System.out.println(res);
}
}
}
Note: There can be other ways of dealing with this problem. But, solving problem using this
method required less lines of code to write.
Comentarios