力扣-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;
    }
};
相关推荐
coder江12 分钟前
二分查找刷题总结
算法
坚持就完事了1 小时前
蓝桥杯中Python常用的库与模块
python·算法
立志成为大牛的小牛1 小时前
数据结构——四十四、平衡二叉树的删除操作(王道408)
数据结构·学习·程序人生·考研·算法
Suckerbin2 小时前
一次LeeCode刷题记录:接雨水
算法
Blossom.1182 小时前
RLHF的“炼狱“突围:从PPO到DPO的工业级对齐实战
大数据·人工智能·分布式·python·算法·机器学习·边缘计算
MobotStone3 小时前
从问答到决策:Agentic AI如何重新定义AI智能体的未来
人工智能·算法
Shemol4 小时前
二叉树的三种迭代遍历(无栈版本)-- 我在马克思主义课上的一些巧思
算法
胖咕噜的稞达鸭4 小时前
进程状态,孤儿进程僵尸进程,Linux真实调度算法,进程切换
linux·运维·算法
RTC老炮4 小时前
webrtc降噪-WienerFilter源码分析与算法原理
算法·webrtc
hweiyu005 小时前
数据结构:数组
数据结构·算法