Skip to content

Latest commit

 

History

History
69 lines (48 loc) · 1.72 KB

File metadata and controls

69 lines (48 loc) · 1.72 KB

中文文档

Description

Given two non-negative integers 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.

Solutions

Python3

class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        n1, n2 = len(num1) - 1, len(num2) - 1
        carry = 0
        res = []
        while n1 >= 0 or n2 >= 0 or carry > 0:
            carry += (0 if n1 < 0 else int(num1[n1])) + (0 if n2 < 0 else int(num2[n2]))
            res.append(str(carry % 10))
            carry //= 10
            n1, n2 = n1 - 1, n2 - 1
        return ''.join(res[::-1])

Java

class Solution {
    public String addStrings(String num1, String num2) {
        int n1 = num1.length() - 1, n2 = num2.length() - 1;
        int carry = 0;
        StringBuilder sb = new StringBuilder();
        while (n1 >= 0 || n2 >= 0 || carry > 0) {
            carry += (n1 < 0 ? 0 : num1.charAt(n1--) - '0') + (n2 < 0 ? 0 : num2.charAt(n2--) - '0');
            sb.append(carry % 10);
            carry /= 10;
        }
        return sb.reverse().toString();
    }
}

...