Search

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.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 {
String input = "";

String val1 = input.split(" ", 0);
String val2 = input.split(" ", 0);
BigInteger a = new BigInteger(val1);
BigInteger b = new BigInteger(val2);
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.

### Recent Posts

See All

#### Golf CodeChef Solution in Java - AskTheCode

CodeChef May Long Challenge Solution | Golf (LKDNGOLF) solution | AskTheCode Golf (LKDNGOLF) solution Problem: It's a lockdown. You’re bored in your house and are playing golf in the hallway. The hall

#### Solubility - CodeChef Solution in Java and C++| AskTheCode

CodeChef May Long Challenge Solution | Solubility (SOLBLTY) solution | AskTheCode Solubility (SOLBLTY) solution Problem: Suppose for a unit rise in temperature, the solubility of sugar in water increa

#### Valid Paths CodeChef Solution in C++ | AskTheCode

CodeChef May Long Challenge Solution | Valid Paths (VPATH) solution | AskTheCode Valid Paths (VPATH) CodeChef solution Problem: You are given a tree with N nodes numbered from 1 to N. A set S of nodes