OJ04:力扣415. 字符串相加

OJ04:力扣415. 字符串相加_第1张图片


OJ04:力扣415. 字符串相加_第2张图片

#思路

这个使用高精度计算,add处理进位,遍历字符串,只要有一个字符串没有为空就一直遍历,最多会遍历5100次,不是太多。

将结果放在ans字符串中返回

#C++代码

class Solution {
public:
    string addStrings(string num1, string num2) {
        int i = num1.length() - 1, j = num2.length() - 1, add = 0;
        // add是进位
        string ans = "";
        while (i >= 0 || j >= 0 || add != 0) {
            // 长度没完,进位不为0
            int x = i >= 0 ? num1[i] - '0' : 0; // 获得当前数字
            int y = j >= 0 ? num2[j] - '0' : 0; // 获得当前数字
            int result = x + y + add;
            ans.push_back('0' + result % 10);
            // 算本位
            add = result / 10;
            // 获得进位
            i -= 1;
            j -= 1;
            // 长度-1
        }
        // 计算完以后的答案需要翻转过来
        reverse(ans.begin(), ans.end());
        return ans;
    }
};

#Python代码:

class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        res = ""
        i, j, carry = len(num1) - 1, len(num2) - 1, 0
        while i >= 0 or j >= 0:
            n1 = int(num1[i]) if i >= 0 else 0
            n2 = int(num2[j]) if j >= 0 else 0
            tmp = n1 + n2 + carry
            carry = tmp // 10
            res = str(tmp % 10) + res
            i, j = i - 1, j - 1
        return "1" + res if carry else res

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