力扣题:高精度运算-1.2

2024-01-07 22:27:45

力扣题-1.2

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

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

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

在这里插入图片描述

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

文章来源:https://blog.csdn.net/yumeng3866/article/details/135375474
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。