Deepak Ananth
Deepak Ananth

Reputation: 15

Multiply string - [Leetcode] Problem with Java

Question is:

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.

Code:

class Solution {
    public String multiply(String num1, String num2) {
        long n1=0, n2=0, res;
        n1 =  Long.parseLong(num1);
        n2 =  Long.parseLong(num2);
        res = n1 * n2;
        String str = Long.toString(res);
        return str;
    }
}

Question is:

Its working properly when I give smaller number is like:

Input :40, 90

Output:3600

Input :100, 2099

Output:209900

If i give input like this:

Input :498828660196, 840477629533

Output:"-3269442614257959980"

But the Actual output is : 419254329864656431168468. I don't know why answer coming like this. am also using long datatype. Anyone explain me and give solution for this problem.

Upvotes: 0

Views: 1179

Answers (3)

Deepak Ananth
Deepak Ananth

Reputation: 15

Thank you guys!

I find the Solution.

class Solution {
    public String multiply(String num1, String num2) {
         if (num1.equals("0") || num2.equals("0")) return "0";
        int l1 = num1.length(), l2 = num2.length(), l = l1 + l2;
        char[] ans = new char[l];
        char[] c1 = num1.toCharArray();
        char[] c2 = num2.toCharArray();
        for (int i = l1 - 1; i >= 0; --i) {
            int c = c1[i] - '0';
            for (int j = l2 - 1; j >= 0; --j) {
                ans[i + j + 1] +=  c * (c2[j] - '0');
            }
        }
        for (int i = l - 1; i > 0; --i) {
            if (ans[i] > 9) {
                ans[i - 1] += ans[i] / 10;
                ans[i] %= 10;
            }
        }
        StringBuilder sb = new StringBuilder();
        int i = 0;
        for (; ; ++i) if (ans[i] != 0) break;
        for (; i < ans.length; ++i) sb.append((char) (ans[i] + '0'));
        return sb.toString();
    }
}

Upvotes: -2

user18098820
user18098820

Reputation:

A Long is stored on 64 bits, with a maximum capacity of 2^63 - 1 (9.223372e+18) so you are out of range. I suggest that you are pushing your test too far. You could have changed to BigInteger if it were not proscribed, or to float, but for the purpose of your question assume that it's ok that these numbers are out range. If you want you could check that the inputs are below 10^9 and throw an out of range error.

Upvotes: 0

Satya Prakash Satyam
Satya Prakash Satyam

Reputation: 27

Because you are storing it in Long and the range of long is up to 10^18 sort of but the answer which will come is of 10^23 range so it is throwing some garbage value as it is out of its range of storing, that is why you have return type of string as you can store it in string not in a long datatype.

Upvotes: 0

Related Questions