Add Strings(C++字符串相加)

解题思路:

(1)首先将两个字符串从尾部开始对齐

(2)设置一个进位C

(3)将短字符串前段补0

class Solution {
public:
    string addStrings(string num1, string num2) {
        int c = 0,temp;
        int i = num1.length()-1, j = num2.length()-1;
        string str = "";
        
        while(i>=0 && j>=0) {
            temp = (num1[i]-'0') + (num2[j]-'0') + c;
            if(temp<10) c = 0,str = to_string(temp)+str;
            else c = 1,str = to_string(temp-10)+str;
            i--,j--;
        }
        
        while(i>=0) {
            temp = (num1[i]-'0') + c;
            if(temp<10) c = 0,str = to_string(temp)+str;
            else c = 1,str = to_string(temp-10)+str;
            i--;
        }
        
        while(j>=0) {
            temp = (num2[j]-'0') + c;
            if(temp<10) c = 0,str = to_string(temp)+str;
            else c = 1,str = to_string(temp-10)+str;
            j--;
        }

        if(c==1) return "1"+str;
        else return str;
        
    }
};

 

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