leetcode-字符串相加

415. 字符串相加

题目中已经说明不能使用库函数直接将输入的字符串转换为整数。这就需要我们自己实现大数加法的逻辑,我们可以从两个字符串的最后一位开始,逐位相加,同时记录进位。如果某一位相加的结果超过10,那么需要向前进位。最后将结果转换为字符串返回

python 复制代码
class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        res = []
        carry = 0
        p1, p2 = len(num1) - 1, len(num2) - 1
        while p1 >= 0 or p2 >= 0:
            x1 = ord(num1[p1]) - ord('0') if p1 >= 0 else 0
            x2 = ord(num2[p2]) - ord('0') if p2 >= 0 else 0
            tmp = x1 + x2 + carry
            carry = tmp // 10
            res.append(tmp % 10)
            p1 -= 1
            p2 -= 1
        if carry:
            res.append(carry)
        return "".join(str(x) for x in res[::-1])
相关推荐
重生之我要进大厂3 小时前
LeetCode 876
java·开发语言·数据结构·算法·leetcode
孙小二写代码5 小时前
[leetcode刷题]面试经典150题之1合并两个有序数组(简单)
算法·leetcode·面试
David猪大卫5 小时前
数据结构修炼——顺序表和链表的区别与联系
c语言·数据结构·学习·算法·leetcode·链表·蓝桥杯
MogulNemenis7 小时前
力扣春招100题——队列
数据结构·算法·leetcode
是小Y啦8 小时前
leetcode 106.从中序与后续遍历序列构造二叉树
数据结构·算法·leetcode
程序猿练习生8 小时前
C++速通LeetCode中等第9题-合并区间
开发语言·c++·leetcode
liuyang-neu8 小时前
力扣 42.接雨水
java·算法·leetcode
Ddddddd_1589 小时前
C++ | Leetcode C++题解之第416题分割等和子集
c++·leetcode·题解
凌肖战10 小时前
力扣上刷题之C语言实现(数组)
c语言·算法·leetcode
Milo_K11 小时前
今日 leetCode 15.三数之和
算法·leetcode