Skip to content

415. Add Strings

Jacky Zhang edited this page Oct 13, 2016 · 2 revisions

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

Note:

  1. The length of both num1 and num2 is < 5100.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

解题思路与"2. add two numbers"类似。

public class Solution {
    public String addStrings(String num1, String num2) {
        if(num1 == null || num1.length() == 0) return num2;
        if(num2 == null || num2.length() == 0) return num1;
        StringBuilder sb = new StringBuilder();
        int len1 = num1.length(), len2 = num2.length();
        int carry = 0;
        for(int i = 0; i < len1 || i < len2; i++) {
            int a = i < len1 ? num1.charAt(len1-1-i)-'0' : 0;
            int b = i < len2 ? num2.charAt(len2-1-i)-'0' : 0;
            sb.append((a+b+carry) % 10);
            carry = (a+b+carry) / 10;
        }
        if(carry > 0) sb.append(1);
        return sb.reverse().toString();
    }
}
Clone this wiki locally