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) {
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.