415. 字符串相加

415. 字符串相加

cpp 复制代码
class Solution 
{
public:
    string addStrings(string num1, string num2)
    {
        //i j分别指向当前字符串的最后一位
        int i = num1.length() - 1;
        int j = num2.length() - 1;
        int add = 0;
        string s = "";
        //不要忽略两个串都遍历完了 但是还有一个进位
        while (i >= 0 || j >= 0 || add != 0) 
        {
            //只要还没遍历完 当前字符变数字
            int x = i >= 0 ? num1[i] - '0' : 0;
            int y = j >= 0 ? num2[j] - '0' : 0;
            int result = x + y + add;
            //计算进位
            add = result / 10;
            //当前位数字变字符 尾插进s 
            s.push_back('0' + result % 10);
            //i j前移
            i -= 1;
            j -= 1;
        }
        reverse(s.begin(), s.end());
        return s;
    }
};
相关推荐
phdsky22 分钟前
【设计模式】抽象工厂模式
c++·设计模式·抽象工厂模式
雾岛听蓝1 小时前
C++ 入门核心知识点(从 C 过渡到 C++ 基础)
开发语言·c++·经验分享·visual studio
xlq223222 小时前
19.模版进阶(上)
c++
yuuki2332332 小时前
【C++】初识C++基础
c语言·c++·后端
小年糕是糕手2 小时前
【C++】类和对象(二) -- 构造函数、析构函数
java·c语言·开发语言·数据结构·c++·算法·leetcode
玫瑰花店2 小时前
SomeIP报文详解
c++·someip
利刃大大2 小时前
【c++中间件】redis介绍 && redis-plus-plus库使用
c++·redis·中间件
永不停转2 小时前
关于 QGraphicsItemGroup 内部项目发生变化后group重新定位的问题
c++·qt
IT永勇3 小时前
C++设计模式-装饰器模式
c++·设计模式·装饰器模式
Murphy_lx3 小时前
std_ofstream
c++