如何添加两个字符串数字(带浮点数)?

2024-04-19 03:14:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我想加上两个数字,实际上是字符串,有浮点数

这是我的代码,用于整数而不是浮点

注意:

我不想用Python的方式

num1= "999"
num2 = "82.2"

# print(float(num1)+float(num2))

输入:

num1= "999"
num2 = "82"
class Solution:
    def addStrings(self, num1, num2):
        i = len(num1) -1
        j = len(num2) -1
        carry =0
        res =[]
        while i>=0 or j >=0:
            a = 0 if i<0 else int(num1[i])
            b = 0 if j<0 else int(num2[j])
            tmp = a +b + carry
            res.append((str(tmp%10)))
            carry =(tmp // 10)
            i -= 1
            j -= 1
        res.reverse()
        res_str = ''.join(res)
        return str(carry)+res_str if carry else res_str
print(Solution().addStrings(num1,num2))

这是预期的输出-1081

如果我像下面这样更改输入,它将不工作。请帮我修改代码


num1= "999"
num2 = "82.25"

or 

num1= "99.11"
num2 = "15.2"

它在java中的解决方式与我想在python中解决它的方式相同

public class AddStrings {

    public static void main(String[] args) {

        //Example 1:
        String str1 = "123.52";
        String str2 = "11.2";
        String ans = new AddStrings().addString(str1, str2);
        System.out.println(ans);

        //Example 2:
        str1 = "110.75";
        str2 = "9";
        ans = new AddStrings().addString(str1, str2);
        System.out.println(ans);
    }

    private static final String ZERO = "0";

    // Time: O(Max (N, M)); N = str1 length, M = str2 length
    // Space: O(N + M)
    public String addString(String str1, String str2) {

        String[] s1 = str1.split("\\.");
        String[] s2 = str2.split("\\.");

        StringBuilder sb = new StringBuilder();

        // step 1. calculate decimal points after.
        // decimal points
        // prepare decimal point.
        String sd1 = s1.length > 1 ? s1[1] : ZERO;
        String sd2 = s2.length > 1 ? s2[1] : ZERO;
        while (sd1.length() != sd2.length()) {
            if (sd1.length() < sd2.length()) {
                sd1 += ZERO;
            } else {
                sd2 += ZERO;
            }
        }
        int carry = addStringHelper(sd1, sd2, sb, 0);

        sb.append(".");

        // Step 2. Calculate the Number before the decimal point.
        // Number
        addStringHelper(s1[0], s2[0], sb, carry);
        return sb.reverse().toString();
    }

    private int addStringHelper(String str1, String str2, StringBuilder sb, int carry) {
        int i = str1.length() - 1;
        int j = str2.length() - 1;
        while (i >= 0 || j >= 0) {
            int sum = carry;

            if (j >= 0) {
                sum += str2.charAt(j--) - '0';
            }
            if (i >= 0) {
                sum += str1.charAt(i--) - '0';
            }
            carry = sum / 10;
            sb.append(sum % 10);
        }
        return carry;
    }
}


Tags: stringifreslengthintsbzerostr
2条回答

我建议将字符串更改为int或float(如果字符串中有“.”)。要在返回中返回字符串,请添加str语句:

class Solution:
    def addStrings(self, num1, num2):
        if ('.' in num1) or ('.' in num2): 
            return str(float(num1) + float(num2))
        else:
            return str(int(num1) + int(num2))

print(Solution().addStrings(num1,num2))

三个案例的输出分别为1081、1081.25和114.31

我将main函数转换为helper函数,因为使用它可以添加字符串的十进制和整数部分

已添加评论

num1 = "99.11"
num2 = "15.98"


class Solution:
    def addStrings(self, num1, num2):
         
        # helper method
        def add_string_helper(num1, num2, carry=0):
            i = len(num1) - 1
            j = len(num2) - 1
            res = []
            while i >= 0 or j >= 0:
                a = 0 if i < 0 else int(num1[i])
                b = 0 if j < 0 else int(num2[j])
                tmp = a + b + carry
                res.append((str(tmp % 10)))
                carry = (tmp // 10)
                i -= 1
                j -= 1
            res.reverse()
            res_str = ''.join(res)
            return str(carry), res_str
        
        # first number, take out integer and decimal part
        number1 = num1.split(".")
        integer1 = number1[0]
        decimal1 = "0" if len(number1) == 1 else number1[1]
        
        # second number, integer and decimal part
        number2 = num2.split(".")
        integer2 = number2[0]
        decimal2 = "0" if len(number2) == 1 else number2[1]
        
        # pass decimal parts of both numbers and add them
        carry, decimal_output = add_string_helper(decimal1, decimal2, 0)
        # pass the carry from decimal additions, and integer parts from both numbers
        carry, integer_output = add_string_helper(integer1, integer2, int(carry))
        

        # generate output string on based on the logic
        output_string = ""
        
        # if there is some decimal part other than zero, then append `.` and its value
        if decimal_output != "0":
            output_string = f"{output_string}.{decimal_output}"
        
        # add integer part
        output_string = f"{integer_output}{output_string}"
        
        # append carry from integer addition if it is not zero
        if carry != "0":
            output_string = f"{carry}{output_string}"
        return output_string


print(Solution().addStrings(num1, num2))

输出

115.09

相关问题 更多 >