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])
相关推荐
Jay_See20 分钟前
Leetcode——239. 滑动窗口最大值
java·数据结构·算法·leetcode
爱爬山的老虎1 天前
【面试经典150题】LeetCode121·买卖股票最佳时机
数据结构·算法·leetcode·面试·职场和发展
雾月551 天前
LeetCode 914 卡牌分组
java·开发语言·算法·leetcode·职场和发展
想跑步的小弱鸡1 天前
Leetcode hot 100(day 4)
算法·leetcode·职场和发展
Fantasydg1 天前
DAY 35 leetcode 202--哈希表.快乐数
算法·leetcode·散列表
jyyyx的算法博客1 天前
Leetcode 2337 -- 双指针 | 脑筋急转弯
算法·leetcode
ゞ 正在缓冲99%…1 天前
leetcode76.最小覆盖子串
java·算法·leetcode·字符串·双指针·滑动窗口
惊鸿.Jh1 天前
【滑动窗口】3254. 长度为 K 的子数组的能量值 I
数据结构·算法·leetcode
想跑步的小弱鸡1 天前
Leetcode hot 100(day 3)
算法·leetcode·职场和发展
SsummerC2 天前
【leetcode100】每日温度
数据结构·python·leetcode