[LeetCode 415] Add Strings(Python)

题目描述

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.

思路

按加法法则计算。用一个整数变量保存当前进位值,用以相加。

代码

class Solution(object):
    def addStrings(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        res=''
        i = len(num1) -1
        j = len(num2) - 1
        # 进位值
        carry = 0
        while i >= 0 and j >= 0:
            sum = int(num1[i]) + int(num2[j]) + carry
            if sum < 10:
                carry = 0
                res = str(sum) + res
            else:
                carry = 1
                res = str(sum%10) + res
            i -= 1
            j -= 1
        while i != -1:
            sum = int(num1[i]) + carry
            if sum < 10:
                carry = 0
                res = str(sum) + res
            else:
                carry = 1
                res = str(sum % 10) + res
            i -= 1
        while j != -1:
            sum = int(num2[j]) + carry
            if sum < 10:
                carry = 0
                res = str(sum) + res
            else:
                carry = 1
                res = str(sum % 10) + res
            j -= 1
        if carry != 0:
            res = str(carry) + res
        return res

你可能感兴趣的:(算法)