力扣-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;
    }
};
相关推荐
生信研究猿7 分钟前
#P4625.第2题-大模型训练显存优化算法
算法
逻辑驱动的ken10 分钟前
Java高频面试考点14
开发语言·数据库·算法·哈希算法
故事还在继续吗14 分钟前
C++17关键特性
开发语言·c++·算法
Rabitebla17 分钟前
【数据结构】消失的数字+ 轮转数组:踩坑详解
c语言·数据结构·c++·算法·leetcode
菜菜的顾清寒19 分钟前
力扣100(20)旋转图像
算法·leetcode·职场和发展
Navigator_Z20 分钟前
LeetCode //C - 1025. Divisor Game
c语言·算法·leetcode
深念Y20 分钟前
王者荣耀与英雄联盟数值设计对比:穿透、乘算与加算、增伤乘算更厉害,减伤加算更厉害
数学·算法·游戏·建模·游戏策划·moba·数值
budingxiaomoli27 分钟前
优选算法-多源bfs解决拓扑排序问题
算法·宽度优先
隔壁大炮27 分钟前
10.PyTorch_元素类型转换
人工智能·pytorch·深度学习·算法
The Chosen One98528 分钟前
算法题目分享(二分算法)
算法·职场和发展·蓝桥杯