Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I am trying to Add two Numbers in a String and Return their summation , but facing an error in the hidden testcase

I was trying to answer this leetcode problem of Adding two Numbers in a String and returning a result. the code works fine for basic test cases, but in the hidden test cases the code fails to return a correct output and instead returns some unrelevent value. im having a hard time understanding that, could someone help?
the Input given in the hidden test case was :
Input
"3876620623801494171"
"6529364523802684779"
Output
"-8040758926105372666"
Expected
"10405985147604178950"

why is producing a negative value?

here is the code:
class Solution {
public String addStrings(String num1, String num2) {

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

       long a,b;
        a=Long.parseLong(num1);
        b=Long.parseLong(num2);
       a= a+b;
        
        num1=String.valueOf(a);
        
        return num1;
        
    }
}

>Solution :

It’s an integer overflow.

Your Value == 10405985147604178950

Long.MAX_VALUE == 9223372036854775807

You could use the BigInteger class to solve the problem.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading