力扣-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;
    }
};
相关推荐
potato_may44 分钟前
链式二叉树 —— 用指针构建的树形世界
c语言·数据结构·算法·链表·二叉树
java修仙传1 小时前
每日一题,力扣560. 和为 K 的子数组
算法·leetcode
ada7_2 小时前
LeetCode(python)——148.排序链表
python·算法·leetcode·链表
点云SLAM2 小时前
点云配准算法之-Voxelized GICP(VGICP)算法
算法·机器人·gpu·slam·点云配准·vgicp算法·gicp算法
资深web全栈开发3 小时前
LeetCode 3625. 统计梯形的数目 II
算法·leetcode·组合数学
橘颂TA3 小时前
【剑斩OFFER】算法的暴力美学——外观数列
算法·leetcode·职场和发展·结构与算法
Liangwei Lin3 小时前
洛谷 P1434 [SHOI2002] 滑雪
算法
c#上位机3 小时前
halcon图像增强之自动灰度拉伸
图像处理·算法·c#·halcon·图像增强
rit84324994 小时前
压缩感知信号恢复算法:OMP与CoSaMP对比分析
数据库·人工智能·算法
Pluchon4 小时前
硅基计划4.0 算法 FloodFill算法
java·算法·leetcode·决策树·逻辑回归·深度优先·图搜索算法