力扣-415.字符串相加

Idea

模拟:竖式加法

从后面往前逐位相加,然后将相加的结果模10,添加到答案字符串中去

最后需要判断一下是否还有进位问题

需要将答案string翻转

AC Code

cpp 复制代码
class Solution {
public:
    string addStrings(string num1, string num2) {
        string ans;
        int l = num1.size() - 1, r = num2.size() - 1;
        int temp = 0;
        while(l >= 0 && r >= 0) {
            int a = num1[l] - '0';
            int b = num2[r] - '0';
            temp += a + b;
            ans += to_string(temp % 10);
            temp /= 10;
            l--;
            r--;
        }
        while(l >= 0) {
            int a = num1[l--] - '0';
            temp += a;
            ans += to_string(temp % 10);
            temp /= 10;
        } 
        while(r >= 0) {
            int b = num2[r--] - '0';
            temp += b;
            ans += to_string(temp % 10);
            temp /= 10;
        }
        if(temp) ans += to_string(temp);
        reverse(ans.begin(),ans.end());
        return ans;
    }
};
相关推荐
Darkwanderor7 小时前
什么数据量适合用什么算法
c++·算法
zc.ovo7 小时前
河北师范大学2026校赛题解(A,E,I)
c++·算法
py有趣7 小时前
力扣热门100题之环形链表
算法·leetcode·链表
py有趣8 小时前
力扣热门100题之回文链表
算法·leetcode·链表
月落归舟9 小时前
帮你从算法的角度来认识二叉树---(二)
算法·二叉树
SilentSlot10 小时前
【数据结构】Hash
数据结构·算法·哈希算法
样例过了就是过了11 小时前
LeetCode热题100 柱状图中最大的矩形
数据结构·c++·算法·leetcode
wsoz12 小时前
Leetcode哈希-day1
算法·leetcode·哈希算法
阿Y加油吧12 小时前
LeetCode 二叉搜索树双神题通关!有序数组转平衡 BST + 验证 BST,小白递归一把梭
java·算法·leetcode