1

Given two numbers as input, return the sum of the numbers. Note that the numbers can be very large and hence are provided as Strings

Sample Input #1:

add("2354725234782357","9999999999999999999999999988888888888")

Sample Output #1:

10000000000000000000002354714123671245

Implementation:

public String add(String str1, String str2) {

    int max = str1.length() > str2.length() ? str1.length() : str2.length();
    int n1[] = new int[max];
    int n2[] = new int[max];
    for (int i = 0; i < str1.length(); i++) {
        n1[i] = str1.charAt(str1.length() - 1 - i);

    }
    for (int i = 0; i < str2.length(); i++) {
        n2[i] = str2.charAt(str2.length() - 1 - i);
    }
    int carry = 0;
    int sum[] = new int[max + 1];
    int k = 0;
    for (k = 0; k < max; k++) {
        sum[k] = (n1[k] + n2[k] + carry) % 10;
        if ((n1[k] + n2[k] + carry) >= 10) {
            carry = 1;
        } else {
            carry = 0;
        }
    }
    sum[max] = carry;
    String result = "";
    return result;

}

I have implemented my logic but I don't know how to get the output as a string.

6
  • 1
    Have a look at BigInteger: docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html Commented Sep 9, 2015 at 7:36
  • Consider padding the two Strings so that they are the same length (by adding 0s to the start of the smallest String, it should make tracking the indices easier Commented Sep 9, 2015 at 7:37
  • @NicholasRobinson using biginteger will not be helpful as i am trying to correct my program with logic. Commented Sep 9, 2015 at 7:40
  • @nisha you think you implement the logic, so where is the result stored? in sum array? Commented Sep 9, 2015 at 7:41
  • @kai , thats is the area where i got stuck ,thats why i needed help. Commented Sep 9, 2015 at 7:47

4 Answers 4

5

Why don't use BigInteger this is much easier and still native java.

private static String add(String s1, String s2)
{
    BigInteger n1 = new BigInteger(s1);
    BigInteger n2 = new BigInteger(s2);
    return n1.add(n2).toString();
}

Anyway, there is one bug in your Code. Dont cast char to int the ascii value is used, which is wrong. Parse it with Character.getNumericValue();

If you have done this, you can concat sum array to a string in reversed order.

Solution:

public static String add(String str1, String str2) {

    int max = str1.length() > str2.length() ? str1.length() : str2.length();
    int n1[] = new int[max];
    int n2[] = new int[max];
    for (int i = 0; i < str1.length(); i++) 
    {
        // conver char to int
        n1[i] = Character.getNumericValue(str1.charAt(str1.length() - 1 - i));
    }
    for (int i = 0; i < str2.length(); i++) {
        // conver char to int
        n2[i] = Character.getNumericValue(str2.charAt(str2.length() - 1 - i));
    }
    int carry = 0;
    int sum[] = new int[max + 1];
    int k = 0;
    for (k = 0; k < max; k++) {
        sum[k] = (n1[k] + n2[k] + carry) % 10;
        if ((n1[k] + n2[k] + carry) >= 10) {
            carry = 1;
        } else {
            carry = 0;
        }
    }
    sum[max] = carry;
    // concat array in reverse order
    StringBuilder sb = new StringBuilder();
    for(int i = sum.length - 1; i >= 0; i--)
        sb.append(sum[i]);
    return sb.toString();
}

Input

add("2354725234782357","9999999999999999999999999988888888888")

Output

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

1 Comment

using bigInteger will not helpful as i am trying to implement it logically.
3

There is a logic error in your code: you are adding the char value of each integer instead of the integer themselves. You can get the numeric value of a char using Character.getNumericValue(char ch).

Then, you can construct the resulting String by looping over the sum array. The loop must be done in reverse order (to get the correct order). Beware of the first value sum[max], if it is 0, we must not add it to the String (otherwise, we will get a value padded with a 0):

public static String add(String str1, String str2) {
    int max = Math.max(str1.length(), str2.length());
    int n1[] = new int[max];
    int n2[] = new int[max];
    for (int i = 0; i < str1.length(); i++) {
        //n1[i] = str1.charAt(str1.length() - 1 - i);
        n1[i] = Character.getNumericValue(str1.charAt(str1.length() - 1 - i));
    }
    for (int i = 0; i < str2.length(); i++) {
        //n2[i] = str2.charAt(str2.length() - 1 - i);
        n2[i] = Character.getNumericValue(str2.charAt(str2.length() - 1 - i));
    }
    int carry = 0;
    int sum[] = new int[max + 1];
    int k = 0;
    for (k = 0; k < max; k++) {
        sum[k] = (n1[k] + n2[k] + carry) % 10;
        if ((n1[k] + n2[k] + carry) >= 10) {
            carry = 1;
        } else {
            carry = 0;
        }
    }
    sum[max] = carry;
    StringBuilder sb = new StringBuilder();
    if (sum[max] > 0) {
        sb.append(String.valueOf(sum[max]));
    }
    for (int i = max - 1; i >= 0; i--) {
       sb.append(String.valueOf(sum[i]));
    }  
    return sb.toString();
}

Note that you can also replace

int max = str1.length() > str2.length() ? str1.length() : str2.length();

with

int max = Math.max(str1.length(), str2.length());

1 Comment

what about if input is add("-9999","999")?
0

I have modified some code:(you can avoid array creation)

public static String add(String str1, String str2) {
    int carry=0;
    StringBuilder sum=new StringBuilder();

    int l1=str1.length();
    int l2=str2.length();

    while(l1>0 && l2>0){
        int s=Character.getNumericValue(str1.charAt(--l1))+Character.getNumericValue(str2.charAt(--l2))+carry;
        if(s<10){
           sum.append(s);
        }else{
            sum.append(s%10);
            carry=s/10;
        }

    }
    if(l2>0){
        while(l2>0){

             int s=Character.getNumericValue(str2.charAt(--l2))+carry;
                if(s<10){
                   sum.append(s);
                }else{
                    sum.append(s%10);
                    carry=s/10;
                }

        }


    }
    if(l1>0){
        while(l2>0){
             int s=Character.getNumericValue(str1.charAt(--l1))+carry;
                if(s<10){
                   sum.append(s);
                }else{
                    sum.append(s%10);
                    carry=s/10;
                }

        }
    }

    if(carry>0){
         sum.append(carry);
    }
    return sum.reverse().toString();

}

2 Comments

thanks but your code fails, two inputs -'1600' '213' your output 813 ,expected output-1813.
your should check first bit for sign
0

You can use a StringBuilder to append all the digits from your int[] from max to 0.

StringBuilder sb = new StringBuilder();
for (int i=max; i>=0; i--)
{
   sb.append(String.valueOf(sum[i]));
}  
String result = sb.toString();

You can also improve this to skip leading zeroes if you want:

boolean leadingZero = true;
StringBuilder sb = new StringBuilder();
for (int i=max; i>=0; i--)
{
   if (sum[i] != 0)
   {
        leadingZero=false;
   }
   if (!leadingZero)
   {
        sb.append(String.valueOf(sum[i]));
   }
}  
String result = sb.toString();

4 Comments

,how can i remove zero ?
@nisha see my answer for this (and a bug in your code).
@Tunaki yes your code working fine, i checked my code i also edit my code n1[i]-48 and n2[i]-48.
@RobAu , thanks your suggestion also works but only issue is 0 appending in begnning ,how to remove that zero?

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.