Java BigInteger Solution
Problem Overview
Original Problem: Java BigInteger | Hackerrank
Difficulty: Easy
Category: Java Standard Library – BigInteger & Math
Description: Given two very large integers, print their sum and product.
Understanding the Problem
The task here is a simple addition and multiplication problem; however, due to the potentially very large numbers, we need to ensure we use a suitable data type like BigIntegers to store them.
Input:
Two lines of input, each line contains one non-negative integer up to 100 digits long.
Output:
Two lines of output:
The sum of the two numbers.
The product of the two numbers.
Initial Reasoning
The original problem gives us no template code so we need to handle all aspects of the program. We will start by reading the numbers and converting them to BigIntegers. We will then perform the operations required. Finally, we will print the output as specified.
Pseudocode
// Main function:
Read the numbers
Convert the numbers to BigInteger
Calculate the sum and product of the numbers
Print the sum and product
Solution Code
// Note this is one of many possible solutions
import java.io.*;
import java.math.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String firstInput= scanner.nextLine();
String secondInput = scanner.nextLine();
// Convert to BigInteger so operations are possible
BigInteger bigFirst = new BigInteger(firstInput);
BigInteger bigSecond = new BigInteger(secondInput );
BigInteger sum = bigFirst.add(bigSecond );
BigInteger product = bigFirst.multiply(bigSecond );
System.out.println(sum);
System.out.println(product);
scanner.close();
}
}