I want to check if the reverse of an signed int
value x
lies inside INT_MAX
and INT_MIN
. For this, I have reversed x
twice and checked if it is equal to the original x
, if so then it lies inside INT_MAX
and INT_MIN
, else it does not.
But online compilers are giving a runtime error, but my g++ compiler is working fine and giving the correct output. Can anybody tell me the reason?
int reverse(int x) {
int tx=x,rx=0,ans;
while(tx!=0){
rx = rx+rx+rx+rx+rx+rx+rx+rx+rx+rx+tx%10;
tx/=10;
}
ans = tx = rx;
rx=0;
while(tx!=0){
rx = rx*10 + tx%10;
tx/=10;
}
while(x%10==0&&x!=0)x/=10;
//triming trailing zeros
if(rx!=x){
return 0;
}else{
return ans;
}
}
ERROR:
Line 6: Char 23: runtime error: signed integer overflow: 1929264870 + 964632435 cannot be represented in type 'int' (solution.cpp)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:15:23
I'm not sure what's wrong with your algorithm, but let me suggest an alternative that avoids doing math and the possibility of integer overflows.
If you want to find of if say,
2147483641
is a valid integer when reversed (e.g.1463847412
), you can do it entirely as string comparisons after converting the initial value to a string and reversing that string.Basic algorithm for a non-negative value it this:
convert integer to string (let's call this string
s
)convert INT_MAX to a string (let's call this string
max_s
)reverse
s
. Handle leading zero's and negative chars appropriately. That is, 120 reversed is "21" and -456 reversed is "-654". The result of this conversion is a string calledrev
.If
rev.length() < s_max.length()
Thenrev
is valid as an integer.If
rev.length() > s_max.length()
, thenrev
is not valid as a integer.If
rev.size() == s_max.length()
, then the reversed string is the same length as INT_MAX as a string. A lexical comparison will suffice to see if it's valid. That isisValid = (rev <= s_max)
orisValid = strcmp(rev, s_max) < 1
The algorithm for a negative value is identical except replace INT_MAX with INT_MIN.