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

Python 如何添加两个字符串数字(带浮点数)?,python,Python,我想加上两个数字,实际上是字符串,有浮点数 这是我的代码,用于整数而不是浮点 注意: num1= "999" num2 = "82" 我不想用蟒蛇的方式 num1= "999" num2 = "82.2" # print(float(num1)+float(num2)) 输入: num1= "999" num2 = "82" 它在java中的解决方式与我想在pytho

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

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

注意:

num1= "999"
num2 = "82"
我不想用蟒蛇的方式

num1= "999"
num2 = "82.2"

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

输入:

num1= "999"
num2 = "82"
它在java中的解决方式与我想在python中解决它的方式相同

公共类AddStrings{
公共静态void main(字符串[]args){
//例1:
字符串str1=“123.52”;
字符串str2=“11.2”;
字符串ans=新的addString().addString(str1,str2);
系统输出打印LN(ans);
//例2:
str1=“110.75”;
str2=“9”;
ans=new AddStrings().addString(str1,str2);
系统输出打印LN(ans);
}
私有静态最终字符串0=“0”;
//时间:O(最大(N,M));N=str1长度,M=str2长度
//空间:O(N+M)
公共字符串addString(字符串str1、字符串str2){
字符串[]s1=str1.split(\\);
字符串[]s2=str2.split(\\);
StringBuilder sb=新的StringBuilder();
//步骤1.计算后的小数点。
//小数点
//准备小数点。
字符串sd1=s1.length>1?s1[1]:零;
字符串sd2=s2.length>1?s2[1]:零;
而(sd1.length()!=sd2.length()){
if(sd1.length()=0 | | j>=0){
整数和=进位;
如果(j>=0){
sum+=str2.charAt(j--)-'0';
}
如果(i>=0){
sum+=str1.字符(i--)-'0';
}
进位=总和/10;
某人追加(总和为10%);
}
返运;
}
}

我建议将字符串更改为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。

我将主函数转换为辅助函数,以便使用它添加字符串的十进制和整数部分

已添加评论

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

为什么不直接使用pythonic函数呢?我不想这样使用。num1=“999”num2=“82.2”print(float(num1)+float(num2))@mkrieger1如果您有Java解决方案,为什么不尝试在Python中使用相同的方法?例如,为什么您的Python从不检查数字中是否有小数点?我不能直接使用Python函数。
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