力扣C++实现字符串相加

题目:字符串相加

力扣C++实现字符串相加_第1张图片

class Solution {
public:
    string addStrings(string num1, string num2) {
        int end1 = num1.size() - 1;
        int end2 = num2.size() - 1;
        string strRet;
        strRet.reserve(end1 > end2 ? end1 + 2 : end2 + 2);//优化:提前开空间
        int next = 0, ret = 0;
        while(end1 >= 0 || end2 >= 0)//都完成结束
        {
            int val1 = end1 >= 0 ? num1[end1] - '0' : 0;
            int val2 = end2 >= 0 ? num2[end2] - '0' : 0;
            int sum = val1 + val2 + next;
            next = sum / 10;
            ret = sum % 10;

            strRet += (ret + '0');
            end1--;
            end2--;
        }
        if(next == 1)//1+9,防止最后有进位
            strRet += '1';
        reverse(strRet.begin(), strRet.end());//优化insert
        return strRet;
    }
};

你可能感兴趣的:(leetcode,c++,算法,c语言)