Contents

Sum of two numbers (with.Java)

   Nov 14, 2023     2 min read

This is a post about the “sum of two numbers” problem.

We’re going to learn about it by solving a coding test problem, reflecting on the problem we solved, and exploring other ways to solve it.

Let’s start with the problem.

Problem

Write a solution function that returns the value of a + b as a string, given two integers greater than or equal to 0.

Example input and output
abresult 
“582”“734”“1316” 
“18446744073709551615”“287346502836570928366”“305793246910280479981” 
“0”“0”“0”“0”

My solution to the problem ####

class Solution {
    public String solution(String a, String b) {
        String answer = "";
        int intA = Integer.parseInt(a);
        int intB = Integer.parseInt(b);
        int sum = intA + intB;
        answer = String.valueOf(sum);
        return answer;
    }
}

Explaining the solution to #####

Initially, you wrote code that converted to the Integer data type, added it, converted it back to a string, and returned it, but the 18446744073709551615 in Testcase 2 did not pass because the integer was too large.

I then solved the problem using long, which is twice the size of the Integer data type.

solved using longs

class Solution {
    public String solution(String a, String b) {
        String answer = "";
        long longA = Long.parseLong(a);
        long longB = Long.parseLong(b);
        long sum = longA + longB;
        answer = String.valueOf(sum);
        return answer;
    }
}

However, even with the long data type, we were unable to pass 18446744073709551615 in Testcase 2.

It’s too big a number.

So we used the BigInteger class to handle very large integer values.

Solving with BigInteger

import java.math.BigInteger;

public class Solution {
    public String solution(String a, String b) {
        String answer = "";
        BigInteger bigA = new BigInteger(a);
        BigInteger bigB = new BigInteger(b);
        BigInteger sum = bigA.add(bigB);
        answer = sum.toString();
        return answer;
    }
}

The above code converts the two input strings to BigInteger objects and adds them using the add method.

It then uses the toString method to convert the result to a string and returns it.

This allows us to accurately handle very large integer values.