0

I try for an exercice to add

String nb = "135";
String nb2 = "135";

Result should be a String of "270"

I have no idea how to do that...I try to make a for loop and make an addition : nb.charAt(i) + nb2.charAt(i) but with no succes, I don't know what I have to do with the carry over.

EDIT : I try to don't use Integer or BigInteger, only String this is why I try to use a for loop.

Thanks for clue.

5
  • Do you have to sum all the digits in the string or simply convert the string to number and sum it? Commented Mar 19, 2020 at 12:57
  • Go from last to first and maintain a carry. Commented Mar 19, 2020 at 12:57
  • What can be the maximum length of the string possible? Commented Mar 19, 2020 at 13:00
  • nb.charAt(i) + nb2.charAt(i) will not do what you think it will do. Commented Mar 19, 2020 at 13:01
  • @vivek_23 no maximum length Commented Mar 19, 2020 at 13:06

8 Answers 8

1

String str = "";

// Calculate length of both String  
int n1 = nb.length(), n2 = nb2.length();  
int diff = n2 - n1;  

// Initially take carry zero  
int carry = 0;  

// Traverse from end of both Strings  
for (int i = n1 - 1; i>=0; i--)  
{  
    // Do school mathematics, compute sum of  
    // current digits and carry  
    int sum = ((int)(nb.charAt(i)-'0') +  
        (int) nb2.charAt(i+diff)-'0') + carry);  
    str += (char)(sum % 10 + '0');  
    carry = sum / 10;  
}  

// Add remaining digits of nb2[]  
for (int i = n2 - n1 - 1; i >= 0; i--)  
{  
    int sum = ((int) nb2.charAt(i) - '0') + carry);  
    str += (char)(sum % 10 + '0');  
    carry = sum / 10;  
}  

// Add remaining carry  
if (carry > 0)  
    str += (char)(carry + '0');  

// reverse resultant String 
return new StringBuilder(str).reverse().toString();
Sign up to request clarification or add additional context in comments.

6 Comments

Awesome, that's exactly what i was looking to do, thank you very much.
@samuel - This program has issues. Try adding 3270 and 270 and it will fail with StringIndexOutOfBoundsException. Did you check my answer?
@ArvindKumarAvinash The bigger number should be swapped that is if you add 270 + 3270 this will work A simple swap will do that.... This is an easy guess.. lol
@SHIVANSHNARAYAN Might be an easy guess but usually answers on SO needs to be complete so that others can learn from it. I am saying this because there is a very less chance they would read comments below the answers.
@vivek_23 sure will do the edit. but I would also advise reading the comments much time s they are also helpful
|
1

try below snippet:

String s1 = "135";
    String s2 = "135";
    String result = Integer.toString (Integer.parseInt(s1)+Integer.parseInt(s2));

4 Comments

What if string is of length 100?
Thanks, but I try to don't use Integer or BigInteger, only String this is why I try to use a for loop
Integer.parseInt will give you an int, not an Integer
@Slackow what OP means is that he can't use the methods in the Integer class, because this is probably a homework question.
1

try converting char to int using Integer.parseInt(nb.charAt(i)) + Integer.parseInt(nb2.charAt(i))

1 Comment

What if string is of length 100?
1

you can use Character.numericValue to give you the integer value of a character, this will probably help you write the method. This method will also return -1 if there is no numeric value or -2 if it is fractional like the character for 1/2

Comments

1

You need to convert the strings to numbers to add them. Let's use BigInteger, just in case the numbers are really big:

String nb  = "135";
String nb2 = "135";

BigInteger num1 = new BigInteger(nb);
BigInteger num2 = new BigInteger(nb2);

String result = num1.add(num2).toString();

4 Comments

What if string is of length 100?
Then we'd have to use BigInteger, but that is not a requirement in the question.
Ok, clarifying from OP.
Thanks, but I try to don't use Integer or BigInteger, only String this is why I try to use a for loop
1

Do it as follows:

public class Main {
    public static void main(String args[]) {
        System.out.println(getSum("270", "270"));
        System.out.println(getSum("3270", "270"));
        System.out.println(getSum("270", "3270"));
    }

    static String getSum(String n1, String n2) {
        StringBuilder sb = new StringBuilder();
        int i, n, cf = 0, nl1 = n1.length(), nl2 = n2.length(), max = nl1 > nl2 ? nl1 : nl2, diff = Math.abs(nl1 - nl2);

        for (i = max - diff - 1; i >= 0; i--) {
            if (nl1 > nl2) {
                n = cf + Integer.parseInt(String.valueOf(n1.charAt(i + diff)))
                        + Integer.parseInt(String.valueOf(n2.charAt(i)));
            } else {
                n = cf + Integer.parseInt(String.valueOf(n1.charAt(i)))
                        + Integer.parseInt(String.valueOf(n2.charAt(i + diff)));
            }
            if (n > 9) {
                sb.append(n % 10);
                cf = n / 10;
            } else {
                sb.append(n);
                cf = 0;
            }
        }
        if (nl1 > nl2) {
            for (int j = i + 1; j >= 0; j--) {
                sb.append(n1.charAt(j));
            }
        } else if (nl1 < nl2) {
            for (int j = i + 1; j >= 0; j--) {
                sb.append(n2.charAt(j));
            }
        }
        return sb.reverse().toString();
    }
}

Output:

540
3540
3540

Comments

1

I would like to propose a much cleaner solution that adds 2 positive numbers and returns the result. Just maintain a carry while adding 2 digits and add carry in the end if carry is greater than 0.

public class Main{
    public static void main(String[] args) {
        System.out.println(addTwoNumbers("135","135"));
    }

    private static String addTwoNumbers(String s1,String s2){
        if(s1.length() < s2.length()) return addTwoNumbers(s2,s1);
        StringBuilder result = new StringBuilder("");
        int ptr2 = s2.length() - 1,carry = 0;
        for(int i=s1.length()-1;i>=0;--i){
             int res = s1.charAt(i) - '0' + (ptr2 < 0 ? 0 : s2.charAt(ptr2--) - '0') + carry;
             result.append(res % 10);
             carry = res / 10;
        }

        if(carry > 0)  result.append(carry);
        return trimLeadingZeroes(result.reverse().toString());
    }

    private static String trimLeadingZeroes(String str){
        for(int i=0;i<str.length();++i){
            if(str.charAt(i) != '0') return str.substring(i); 
        }

        return "0";
    }
}

Demo: https://onlinegdb.com/Sketpl-UL

Comments

1

Try this i hope it works for you

Code

public static int convert_String_To_Number(String numStr,String numStr2) {
                char ch[] = numStr.toCharArray();
                char ch2[] = numStr2.toCharArray();
                int sum1 = 0;
                int sum=0;
                //get ascii value for zero
                int zeroAscii = (int)'0';
                for (char c:ch) {
                    int tmpAscii = (int)c;
                    sum = (sum*10)+(tmpAscii-zeroAscii);

                }
for (char d:ch2) {
                    int tmpAscii = (int)d;
                    sum1 = (sum*10)+(tmpAscii-zeroAscii);

                }

                return sum+sum1;
            }
            public static void main(String a[]) {
                System.out.println("\"123 + 123\" == "+convert_String_To_Number("123" , "123"));

            }
        }

2 Comments

sum and sum1 would yield the same result here, you never use the second array. Also, this is the equivalent of using parseInt, it doesn't account for when the String is higher than the integer limit.
Yes.Thanks for highlighting that for me.I have edited the code.

Your Answer

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