Seawolf 发表于 2020-8-4 23:03:58

Leetcode 415. Add Strings

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.

class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
      i, j = len(num1) - 1, len(num2) - 1
      carry = 0
      total = 0
      result = ''
      while i >= 0 or j >= 0:
            total = carry
            if i >= 0:
                total += ord(num1) - 48
            if j >= 0:
                total += ord(num2) - 48
            result += str(total % 10)
            carry = total // 10
            i -= 1
            j -= 1
      if carry > 0:
            result += str(carry)
      return result[::-1]
页: [1]
查看完整版本: Leetcode 415. Add Strings