[leetcode]文字列加算

5199 ワード

415.文字列加算
2つの文字列形式の非負の整数num 1とnum 2を与え、それらの和を計算する.
注意:
num1  num2        5100.
num1  num2        0-9.
num1  num2          。
          BigInteger  ,                    。

C++解法:
class Solution {
public:
    string addStrings(string num1, string num2) {
        string ans = "";
        int c = 0;
        int i = num1.size() - 1;
        int j = num2.size() - 1;
        while (i >= 0 || j >= 0 || c > 0)
        {
            if (i >= 0)
            {
                c += (num1[i--] - '0');
            }
            else
            {
                c += 0;
            }

            if (j >= 0)
            {
                c += (num2[j--] - '0');
            }
            else
            {
                c += 0;
            }
            ans = char(c % 10 + '0') + ans;
            c /= 10;
        }
        return ans;
    }
};