力扣-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;
    }
};
相关推荐
爱编程的小吴15 小时前
【力扣练习题】热题100道【哈希】189. 轮转数组
算法·leetcode·哈希算法
wjykp15 小时前
105~108SVMf
算法
leoufung15 小时前
LeetCode 322. Coin Change:从错误思路到正确一维 DP
算法·leetcode·职场和发展
旧梦吟15 小时前
脚本网页 双子星棋
算法·flask·游戏引擎·css3·html5
ullio15 小时前
arc205d - Non-Ancestor Matching
算法
wa的一声哭了16 小时前
内积空间 正交与正交系
java·c++·线性代数·算法·矩阵·eclipse·云计算
SWAGGY..16 小时前
数据结构学习篇(8)---二叉树
数据结构·学习·算法
星轨初途16 小时前
牛客小白月赛126
开发语言·c++·经验分享·笔记·算法
leoufung16 小时前
动态规划DP 自我提问模板
算法·动态规划
爱编程的小吴16 小时前
【力扣练习题】热题100道【哈希】560. 和为 K 的子数组
算法·leetcode·哈希算法