C++ ---字符串相加

字符串相加

题目描述:
C++ ---字符串相加_第1张图片
题目来源:力扣

class Solution {
public:
    string addStrings(string num1, string num2) {
        int end1 = num1.size()-1,end2 = num2.size()-1;
        string retstr;
        int next = 0;//进位
        while(end1 >= 0 || end2 >= 0)
        {
            
            int val1 = 0;
            if(end1 >= 0)
            {
                val1 = num1[end1] - '0';
                --end1;
            }
            int val2 = 0;
            if(end2 >= 0)
            {
                val2 = num2[end2] - '0';
                --end2;
            }
            int ret = val1+val2+next;
            if(ret > 9)
            {
                ret -=10;
                next = 1;
            }
            else
                next = 0;
            retstr.insert(retstr.begin(),'0'+ret);
        }
        if(next == 1)
            retstr.insert(0,1,'1');
       
        return retstr;
    }
};

你可能感兴趣的:(C++,字符串,leetcode,算法)