 # Can somebody tell me what's wrong with my code?

#1

public class Solution {
public int reverse(int A) {
String s="";
long d=0;
int n=0;
if(A<0)
n=1;
A=Math.abs(A);
while(A>0)
{
d=A%10;
s=s+d;
A=A/10;
}
A=Integer.parseInt(s);
if(A<Integer.MIN_VALUE || A>Integer.MAX_VALUE)
return 0;
if(n==1)
return -A;
else
return A;
}
}

#2

In this try capturing the exception when the parsing fails rather than after. In your solution you’re checking for the limits of the num after trying to parse it, which in the case where it fails, it is of no use as an exception will be throw and the rest of the code doesn’t run. If it succeeds the second line is moot.

#3

Check at highlighted code for clue.
int Solution::reverse(int A) {
int mul = 1;
if(A<0){
mul = -1;
}
A = abs(A);
// cout << A << endl;
int B=0;
while(A>0){
B = B10+(A%10);
// cout << B << endl;
A/=10;
if(mul==1){
`if(((B)>INT_MAX/10 && A!=0) || (B==INT_MAX && B%10>INT_MAX%10)){`
return 0;
}
}
else if(mul==-1){
`if(((B*mul)<INT_MIN/10 && A!=0) || (B*mul==INT_MIN/10 && (B*mul)%10<INT_MIN%10)){`
return 0;
}
}
}
return B
mul;
}

#4

Instead of using s as string you can use s as long long int and apply s = s*10 + d for reversing A instead of s = s + d for as a string.