public class Solution {
public boolean isPalindrome(int x) {
int sum = 0,target = x;
while (x > 0) {
int temp = x % 10;
x /= 10;
sum = sum * 10 + temp;
}
return sum == target;
}
}
@erenalgan2, run it for yourself. it returns false. note that target is not used for any arithmetic operations. it is only used for the last comparison.
Clearly you don't understand the point here. It exploits Java "overflow" and "underflow" implementation which is explained here: http://stackoverflow.com/questions/3001836/how-does-java-handle-integer-underflows-and-overflows-and-how-would-you-check-fo
This solution would sure work in Java but not in C, C++ or C#. Because it is language dependent and algorithm assumes so much.
Ok, here is an example for you to understand:
Let's assume x is 2147483647, a valid integer. Here is the steps for that algorithm:
This is the interesting part. sum is 32 bit integer (4 bytes) in most of the languages (Java, C#, C, C++ etc.). You CANNOT represent 7463847412 with 4 bytes since 2147483647 is the MAX INTEGER value. In java though, in the 10th iteration, when you try to multiply 746384741 * 10 and add 2, Java handles the overflow for you and sets it to a some negative number (remember http://stackoverflow.com/questions/3001836/how-does-java-handle-integer-underflows-and-overflows-and-how-would-you-check-fo). Therefore at the end of the iteration, you verify sum != target and algorithm returns false.
Try to do the same thing in C#, it will throw OverflowException (https://msdn.microsoft.com/en-us/library/system.overflowexception(v=vs.110).aspx).
Hence, this algorithm assumes so much and is not correct!
P.S. You can debug it and see the value of sum in the 10th iteration :)