【问题标题】:Multiply string - [Leetcode] Problem with JavaMultiply string - [Leetcode] Problem with Java
【发布时间】:2022-12-27 20:32:16
【问题描述】:

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.

【问题讨论】:

标签: java logic


【解决方案1】:

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.

【讨论】:

  • oh alright, How to fix this problem because they asking convert the string to integer and then multiply the both string value to return the answer as string
  • @DeepakAnanth you may easily find various ways of solving the problem in its discussion page. Leetcode's discussion page is the best resource you can get for this.
【解决方案2】:

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.

【讨论】:

  • Rule is must not use any built-in BigInteger library
猜你喜欢
  • 2022-10-25
  • 2022-12-19
  • 2022-12-28
  • 2022-12-28
  • 1970-01-01
  • 2022-12-26
  • 2021-02-13
  • 2022-12-02
  • 1970-01-01
相关资源
最近更新 更多