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])

转载于:https://www.cnblogs.com/salmd/p/5964545.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值