Search code examples
javalogic

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.


Solution

  • 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();
        }
    }