力扣题:高精度运算-1.2

力扣题-1.2

[力扣刷题攻略] Re:从零开始的力扣刷题生活

力扣题1:415. 字符串相加

解题思想:从后往前遍历两个字符串,然后进行相加即可

力扣题:高精度运算-1.2_第1张图片

class Solution(object):
    def addStrings(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        i = len(num1)-1
        j = len(num2)-1
        flag = 0
        result = ""
        while i >= 0 and j >= 0:
            if int(num1[i]) + int(num2[j]) + flag >=10:
                temp = str(int(num1[i]) + int(num2[j]) + flag - 10)
                result = temp + result 
                flag = 1
            else:
                temp = str(int(num1[i]) + int(num2[j]) + flag)
                result = temp + result 
                flag = 0
            i = i - 1
            j = j - 1
        while i >= 0:
            if int(num1[i]) + flag >=10:
                temp = str(int(num1[i]) + flag - 10)
                result = temp + result 
                flag = 1
            else:
                temp = str(int(num1[i]) + flag)
                result = temp + result 
                flag = 0
            i = i - 1
        while j >= 0:
            if int(num2[j]) + flag >=10:
                temp = str(int(num2[j]) + flag - 10)
                result = temp + result 
                flag = 1
            else:
                temp = str(int(num2[j]) + flag)
                result = temp + result 
                flag = 0
            j = j - 1
        if flag == 1:
            result = '1' + result 
        return result
class Solution {
public:
    string addStrings(string num1, string num2) {
int i = num1.length() - 1;
        int j = num2.length() - 1;
        int flag = 0;
        string result = "";

        while (i >= 0 && j >= 0) {
            int sum = (num1[i] - '0') + (num2[j] - '0') + flag;
            result = to_string(sum % 10) + result;
            flag = sum / 10;
            i--;
            j--;
        }

        while (i >= 0) {
            int sum = (num1[i] - '0') + flag;
            result = to_string(sum % 10) + result;
            flag = sum / 10;
            i--;
        }

        while (j >= 0) {
            int sum = (num2[j] - '0') + flag;
            result = to_string(sum % 10) + result;
            flag = sum / 10;
            j--;
        }

        if (flag > 0) {
            result = to_string(flag) + result;
        }

        return result;
    }
};

你可能感兴趣的:(leetcode,算法,职场和发展)