自学内容网 自学内容网

LeetCode 415.字符串相加 C++写法

LeetCode 415.字符串相加 C++写法

image-20240721185100494

思路🤔:

  首先不能用stoi和tostring来做,如果给一个很大的数那一定存不下。我们可以从后往前一位一位的取,创建一个变量存储进位用于计算下一位数,之后取模得到当前数字,每一位尾插在新创建的string中,完成所有尾插后用reverse进行逆置就是我们要得到的结果。

image-20240721184828079

代码🔎:

class Solution {
public:
    string addStrings(string num1, string num2) {
        int end1 = num1.size() - 1;
        int end2 = num2.size() - 1;
        int next = 0; //存进位
        string str; //用于存结果
        while(end1 >= 0 || end2 >= 0) //两个字符串都走完才算完成相加
        {
            int x1 = end1 >= 0 ? num1[end1] - '0' : 0; //当一个已经走完了,那么就为0,不再相加
            int x2 = end2 >= 0 ? num2[end2] - '0' : 0;
            int ret = x1 + x2 + next; //计算相加后为多少
            next = ret / 10; //取进位
            ret = ret % 10; //取当前数字用于尾插
            str += ('0' + ret); //尾插
            end1--;
            end2--;
        }
        if (next == 1) //防止出现num1=9,num2=1的情况
            str += '1';
        reverse(str.begin(),str.end()); //逆置
        return str;
    }
};

image-20240721185608690


原文地址:https://blog.csdn.net/m0_63816268/article/details/140622842

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!