跳转至

415. Add Strings

Leetcode Math

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

Note:

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

分析

考查数字和字符串的基本操作。

public String addStrings(String num1, String num2) {
    if (num1 == null || num2 == null) return "";
    int n1 = num1.length(), n2 = num2.length();
    int i = 0, carry = 0;
    int d1, d2, digit;
    StringBuilder s = new StringBuilder();
    while (i < n1 || i < n2 || carry > 0) {
        d1 = 0; d2 = 0;
        if (i < n1) d1 = num1.charAt(n1 - 1 - i) - '0';
        if (i < n2) d2 = num2.charAt(n2 - 1 - i) - '0';
        digit = d1 + d2 + carry;
        if (digit > 9) {carry = 1; digit -= 10;}
        else carry = 0;

        s.append(digit);
        i++;
    }

    return s.reverse().toString();
}