[leetcode]字符串相加

415. 字符串相加

给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。

注意:

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;
    }
};

你可能感兴趣的:(leetcode)