简体   繁体   English

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

[英]How to add two string numbers (with floating point)?

I want add two numbers which is actually string and having floating point.我想添加两个数字,它们实际上是字符串并且具有浮点数。

Here is my code which is working for integers and not for float.这是我的代码,它适用于整数而不是浮点数。

NOTE:笔记:

I do not want to use the pythonic way.我不想使用 pythonic 方式。

num1= "999"
num2 = "82.2"

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

Input:输入:

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))

This is giving output as expected - 1081这正如预期的那样给 output - 1081

If I change the input like below it is not working.如果我像下面这样更改输入,则它不起作用。 Please help me modify my code.请帮我修改我的代码。


num1= "999"
num2 = "82.25"

or 

num1= "99.11"
num2 = "15.2"

The way it is solved in java same way I want to solve it in python.它在 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;
    }
}

I suggest to change the strings to int or float (in case there is a '.' in the string).我建议将字符串更改为 int 或 float(以防字符串中有 '.')。 To get strings back in the return add the str statement:要在 return 中取回字符串,请添加 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))

The output is 1081, 1081.25 and 114.31 for your three cases.对于您的三种情况,output 是 1081、1081.25 和 114.31。

I converted you main function to helper function as use it add decimal and integer part of strings.我将您的主要 function 转换为助手 function ,因为它使用它添加十进制和 integer 部分字符串。

Comments have been added.已添加评论。

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))

Output Output

115.09

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM