[leetcode]Python实现-415. 字符串相加

415. 字符串相加

描述

给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。

注意:

num1 和num2 的长度都小于 5100.
num1 和num2 都只包含数字 0-9.
num1 和num2 都不包含任何前导零。
你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。

class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        flag = 0
        if len(num1) > len(num2):
            short = num2
            long  = num1
        elif len(num1) == len(num2):
            flag = 1
            short = num2
            long  = num1
        else:
            short = num1
            long = num2
        in_count = 0
        result = ''
        for i in range(len(short)-1, -1, -1):
            temp = ord(short[i]) + ord(long[i+len(long)-len(short)]) - 48 * 2
            temp += in_count
            if temp > 19:
                in_count = 2
                temp -= 20
            elif temp > 9:
                in_count = 1
                temp -= 10
            else:
                in_count = 0
            result += str(temp)
        if flag == 1:
            if in_count:
                result += str(in_count)
            result = result[::-1]
        else:
            j = len(long) - len(short)
            if in_count:
                for j in range(len(long)-len(short)-1,-1,-1):
                    temp = ord(long[j]) + in_count - 48
                    if temp > 9:
                        in_count = 1
                        temp -= 10
                        result += str(temp)
                    else:
                        result += str(temp)
                        in_count = 0
                        result = long[0:j] + result[::-1]
                        break
                if in_count:
                    result = '1' + result[::-1]
            else:
                result = long[0:j] + result[::-1]
        return result
       

在这里插入图片描述
总结一下:
这题涉及到的逻辑判断较多。。所以我目前还是有点混乱,调试了五次一个小时才成功通过。。。昨天还想嘲讽leetcode,今天不敢了。
解题方法就是将字符转换为ASCII码做运算。。。。。。其实跟转为int没啥区别我觉得,但我想不出其他方法来,还是太菜

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值