1. 程式人生 > 其它 >字串相加—leetcode415

字串相加—leetcode415

技術標籤:劍指offer+leetcode字串演算法leetcode

給定兩個字串形式的非負整數num1num2,計算它們的和。

提示:

  1. num1num2的長度都小於 5100
  2. num1num2都只包含數字0-9
  3. num1num2都不包含任何前導零
  4. 你不能使用任何內建 BigInteger 庫,也不能直接將輸入的字串轉換為整數形式

class Solution {
public:
    string addStrings(string num1, string num2) {
        int N1 = num1.length();
        int N2 = num2.length();
        int index1 = N1-1;
        int index2 = N2-1;
        string res = "";
        int t = 0;
        while(index1>=0 && index2>=0){
            int temp = (num1[index1--]-'0')+(num2[index2--]-'0');
            res += (temp+t)%10+'0';
            t = (temp+t)/10;
        }
        if(index1<0){
            while(index2>=0){
                int temp = (num2[index2--]-'0');
                res += (temp+t)%10+'0';
                t = (temp+t)/10;
            }
        }else{
            while(index1>=0){
                int temp = (num1[index1--]-'0');
                res += (temp+t)%10+'0';
                t = (temp+t)/10;
            }
        }
        if(t!=0)
            res += 1+'0';
        reverse(res.begin(),res.end());
        return res;
    }
};