415. Add Strings

problem

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

将0-9(非负数)组成的字符串,相加返回相加后的str

不能用内置的类型转换函数

solution

  • 实现的比较笨拙,两个字典实现字符 数字互相转换

  • 这个思路其实是实现的类型转换,不是字符串相加

  • 继续优化的话,可以将loop缩减为1个

class Solution(object):
    def addStrings(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        dictStoN = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
        dictNtoS = dict([(v,k) for k,v in dictStoN.iteritems()])
        nums = 0 
        res = ''
        #num1 = sum(map(dictNum[num1[x]]*10**x for x in range(len(num1))[::-1])
        
        n = 0
        for x in num1[::-1]:
            nums += dictStoN[x]*10**n
            n += 1
            
        n = 0
        for x in num2[::-1]:
            nums += dictStoN[x]*10**n
            n += 1
            
        if nums is not 0:    
            while 1:
                if nums < 10:
                    res += dictNtoS[nums]
                    break
                nums,mid = divmod(nums,10) 
                res += dictNtoS[mid]
        else:
            res = '0'
        
        return res[::-1]
            

discuss

def addStrings(self, num1, num2):
    z = itertools.izip_longest(num1[::-1], num2[::-1], fillvalue='0')
    res, carry, zero2 = [], 0, 2*ord('0')
    for i in z:
        cur_sum = ord(i[0]) + ord(i[1]) - zero2 + carry
        res.append(str(cur_sum % 10))
        carry = cur_sum // 10
    return ('1' if carry else '') + ''.join(res[::-1])
posted @ 2016-10-15 15:30  Salmd  阅读(227)  评论(0)    收藏  举报