# Straightforward java code

• ``````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;
}
``````

}

• how does this handle number overflow?

• ++wpc.. Really how?

• @wpc , no need to handle overflow, as long as the input x is a valid integer.

• BTW, great simplicity. reversing the number and see if we can build the same number from end to start

• @yanggao please tell me what happens when x is 2147483647 which is a valid integer

• @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.

• I still don't understand it. we are building sum from zero up. so if the input is valid, we don't need to worry about integer overflow. do we?

• 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:

1. iteration: temp = 7, x = 214748364 sum = 7
2. iteration: temp = 4, x = 21474836 sum = 74
3. iteration: temp = 6, x = 2147483 sum = 746
.
.
.
4. iteration: temp = 1, x = 2 sum = 746384741
5. iteration: temp = 2, x = 0 sum = 7463847412 (on paper, not in computers)

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 :)

• How about set sum to be "long", and convert it back to int at the last comparison?

• Guys, "int sum = 0,target = x" breaks the restriction "do this without extra space".

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.