1

Given two non-negative numbers num1 and num2 represented as strings, return the sum of num1 and num2.

The length of both num1 and num2 is less than 5100.

Both num1 and num2 contain only digits 0-9.

Both num1 and num2 do not contain any leading zeros.

You must not use any built-in BigInteger library or convert the inputs to integer directly.

I tried my solution but it doesn't work. Suggestions?

public class Solution {
    public String addStrings(String num1, String num2) {
        double multiplier = Math.pow(10, num1.length() - 1);
        int sum = 0;

        for (int i = 0; i < num1.length(); i++){
            sum += ((((int) num1.charAt(i)) - 48) * multiplier);
            multiplier /= 10;
        }

        multiplier = Math.pow(10, num2.length() - 1);

        for (int i = 0; i < num2.length(); i++){
            sum += ((((int) num2.charAt(i)) - 48) * multiplier);
            multiplier /= 10;
        }

        return "" + sum;
    }    
}
2
  • 2
    Please give an example input, and the example output. Commented Oct 14, 2016 at 17:47
  • 1
    You are adding the numbers from the left to the right instead of vice versa. You are not adding the carry from the previous stage. You use int for sum, but your input can be > 5000 digits? Commented Oct 14, 2016 at 17:52

8 Answers 8

5

You must not use any built-in BigInteger library or convert the inputs to integer directly.

Note that you are adding two integers of up to 5100 digits each. That is not that max value, but the max number of digits.

An int (your sum variable) cannot hold values like that. BigInteger can, but you're not allowed to use it.

So, add the numbers like you would on paper: Add last digits, write lower digit of the sum as last digit of result, and carry-over a one if needed. Repeat for second-last digit, third-last digit, etc. until done.

Since the sum will be at least the number of digits of the longest input value, and may be one longer, you should allocate a char[] of length of longest input plus one. When done, construct final string using String(char[] value, int offset, int count), with an offset of 0 or 1 as needed.

Sign up to request clarification or add additional context in comments.

Comments

3

The purpose of this question is to add the numbers in the string form. You should not try to convert the strings to integers. The description says the length of the numbers could be up to 5100 digits. So the numbers are simply too big to be stored in integers and doubles. For instance In the following line:

double multiplier = Math.pow(10, num1.length() - 1);

You are trying to store 10^5100 in a double. In IEEE 754 binary floating point standard a double can a store number from ±4.94065645841246544e-324 to ±1.79769313486231570e+308. So your number won't fit. It will instead turn into Infinity. Even if it fits in double it won't be exact and you will encounter some errors in your follow up calculations.

Because the question specifies not to use BigInteger or similar libraries you should try and implement string addition yourself.

This is pretty straightforward just implement the exact algorithm you follow when you add two numbers on paper.

4 Comments

Great minds think alike: We both advised doing it the way you do it on paper. :-)
@Andreas I advised the last guy to do it on paper too :) link
@Tempux I always wondered can double be used to store and retrieve 128 bit integer? As there is no container to store 128 bit integer in traditional language. It would be useful to store IPv6 in double then :)
@KaidulIslam Maybe it can but you will lose the precision for sure.
3

Here is working example of adding two strings without using BigInteger using char array as intermediate container. The point why double can't be used has been explained on @Tempux answer. Here the logic is similar to how adding two numbers on paper works.

public String addStrings(String num1, String num2) {
    int carry = 0;
    int m = num1.length(), n = num2.length();
    int len = m < n ? n : m;
    char[] res = new char[len + 1]; // length is maxLen + 1 incase of carry in adding most significant digits
    for(int i = 0; i <= len ; i++) {
        int a = i < m ? (num1.charAt(m - i - 1) - '0') : 0;
        int b = i < n ? (num2.charAt(n - i - 1) - '0') : 0;
        res[len - i] = (char)((a + b + carry) % 10 + '0');
        carry = (a + b + carry) / 10;
    }
    return res[0] == '0' ? new String(res, 1, len) : new String(res, 0, len + 1);
}

This snippet is relatively small and precise because here I didn't play with immutable String which is complicated/messy and yield larger code. Also one intuition is - there is no way of getting larger output than max(num1_length, num2_length) + 1 which makes the implementation simple.

Comments

0

You have to addition as you do on paper

you can't use BigInteger and the String Length is 5100, so you can not use int or long for addition. You have to use simple addition as we do on paper.

class AddString
{
public static void main (String[] args) throws java.lang.Exception
{
    String s1 = "98799932345";
    String s2 = "99998783456";
    //long n1 = Long.parseLong(s1);
    //long n2 = Long.parseLong(s2);
    System.out.println(addStrings(s1,s2));
    //System.out.println(n1+n2);
}
public static String addStrings(String num1, String num2) {
    StringBuilder ans = new StringBuilder("");
    int n = num1.length();
    int m = num2.length();
    int carry = 0,sum;
    int i, j;
    for(i = n-1,j=m-1; i>=0&&j>=0;i--,j--){
        int a = Integer.parseInt(""+num1.charAt(i));
        int b = Integer.parseInt(""+num2.charAt(j));
        //System.out.println(a+" "+b);
        sum = carry + a + b;
        ans.append(""+(sum%10));
        carry = sum/10;
    }
    if(i>=0){
        for(;i>=0;i--){
            int a = Integer.parseInt(""+num1.charAt(i));
            sum = carry + a;
            ans.append(""+(sum%10));
            carry = sum/10;
        }
    }
    if(j>=0){
        for(;j>=0;j--){
            int a = Integer.parseInt(""+num2.charAt(j));
            sum = carry + a;
            ans.append(""+(sum%10));
            carry = sum/10;
        }
    }
    if(carry!=0)ans.append(""+carry);
    return ans.reverse().toString();
}   
}

You can run the above code and see it works in all cases, this could be written in more compact way, but that would have been difficult to understand for you.

Hope it helps!

Comments

0

you can use this one that is independent of Integer or BigInteger methods

public String addStrings(String num1, String num2) {
    int l1 = num1.length();
    int l2 = num2.length();
    if(l1==0){
        return num2;
    }
    if(l2==0){
        return num1;
    }
    StringBuffer sb = new StringBuffer();
    int minLen = Math.min(l1, l2);
    int carry = 0;
    for(int i=0;i<minLen;i++){
        int ind = l1-i-1;
        int c1 = num1.charAt(ind)-48;
        ind = l2-i-1;
        int c2 = num2.charAt(ind)-48;
        int add = c1+c2+carry;
        carry = add/10;
        add = add%10;
        sb.append(add);
    }

    String longer = null;
    if(l1<l2){
        longer = num2;
    }
    else if(l1>l2){
        longer = num1;
    }
    if(longer!=null){
        int l = longer.length();
        for(int i=minLen;i<l;i++){
            int c1 = longer.charAt(l-i-1)-48;
            int add = c1+carry;
            carry = add/10;
            add = add%10;
            sb.append(add);
        }
    }
    return sb.reverse().toString();
}

Comments

0

The method takes two string inputs representing non-negative integers and returns the sum of the integers as a string. The algorithm works by iterating through the digits of the input strings from right to left, adding each digit and any carryover from the previous addition, and appending the resulting sum to a StringBuilder. Once both input strings have been fully processed, any remaining carryover is appended to the output string. Finally, the string is reversed to produce the correct output order.

Hope this will solve the issue.!

public string AddStrings(string num1, string num2) 
{
    int i = num1.Length - 1, j = num2.Length - 1, carry = 0;
    StringBuilder sb = new StringBuilder();
    while (i >= 0 || j >= 0 || carry != 0) {
        int x = i >= 0 ? num1[i--] - '0' : 0;
        int y = j >= 0 ? num2[j--] - '0' : 0;
        int sum = x + y + carry;
        sb.Append(sum % 10);
        carry = sum / 10;
    }
    char[] chars = sb.ToString().ToCharArray();
    Array.Reverse(chars);
    return new string(chars);
}

Comments

-1

Previous solutions have excess code. This is all you need.

class ShortStringSolution {
    static String add(String num1Str, String num2Str) {
        return Long.toString(convert(num1Str) + convert(num2Str));
    }

    static long convert(String numStr) {
        long num = 0;
        for(int i = 0; i < numStr.length(); i++) {
            num = num * 10 + (numStr.charAt(i) - '0');
        }
        return num;
    }
}

class LongStringSolution {

    static String add(String numStr1, String numStr2) {
        StringBuilder result = new StringBuilder();
        int i = numStr1.length() - 1, j = numStr2.length() - 1, carry = 0;
        while(i >= 0 || j >= 0) {
            if(i >= 0) {
                carry += numStr1.charAt(i--) - '0';
            }
            if(j >= 0) {
                carry += numStr2.charAt(j--) - '0';
            }
            if(carry > 9) {
                result.append(carry - 10);
                carry = 1;
            } else {
                result.append(carry);
                carry = 0;
            }
        }
        if(carry > 0) {
            result.append(carry);
        }
        return result.reverse().toString();
    }
}

public class Solution {

    static String add(String numStr1, String numStr2) {
        if(numStr1.length() < 19 && numStr2.length() < 19) {
            return ShortStringSolution.add(numStr1, numStr2);
        }
        return LongStringSolution.add(numStr1, numStr2);
    }
}

2 Comments

The question states that the numbers can have over 5000 digits. Your program will fail for much smaller input.
Ok, I amended the answer to account for long strings. It is still less code than other answers.
-2

For the sake of comprehension of the question

your method's name is addition

you are trying to do a power operation but the result is stored in a variable named multiplication...

there is more than one reason why that code doesnt work...

You need to do something like

Integer.parseInt(string)

in order to parse strings to integers

here the oficial doc

1 Comment

"You must not [...] convert the inputs to integer directly" means that Integer.parseInt(string) is not allowed. Besides, that method will crash and burn if given an input of more than 10 digits, and input can be up to 5100 digits long: "The length of both num1 and num2 is < 5100."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.