-2

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.

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

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.

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

Dock
  • 444
  • 5
  • 13
NIMI
  • 73
  • 10

2 Answers2

0

I suggest to change the strings to int or float (in case there is a '.' in the string). To get strings back in the return add the str statement:

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
Henry
  • 127
  • 1
  • 2
  • 9
0

I converted you main function to helper function as use it add decimal and integer part of strings.

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

115.09
gsb22
  • 2,112
  • 2
  • 10
  • 25