Neat AC java code. O(n) time complexity.


  • 31
    H
    public boolean isPalindrome(int x) {
            int palindromeX = 0;
            int inputX = x;
            while(x>0){
                palindromeX = palindromeX*10 + (x % 10);
                x = x/10;
            }
            return palindromeX==inputX;	
        }

  • 0
    D

    very nice try!


  • 0
    Y

    consider int overflow ? such as 1000000003 and 3000000001 is overflow......


  • 0
    E

    Amazing! Just add check condition as follows and u are done.
    if(x < 0 || x == Integer.MAX_VALUE)
    return false;


  • 0
    H

    Good point! Actually I did not consider overflow when writing the code... But it turns out that overflow is automatically handled: palindromeX will result in a negative number because of overflow, and that makes it never equals to the input number x...


  • 0
    W

    Same concern, it will be overflow for some case.


  • 0
    Z

    use long long to store palindromeX


  • 0
    R

    OJ considers negative numbers as non-palindrome. Though, your solution does not handles this case explicitly - seems to me that it is taken care of as a side effect of your algorithm. For ex: if x = -121, palindromeX = 121 by the end of the for loop which is not equal to x (-121). But, there is really no need to go through the for loop, you can return false if x < 0. Otherwise, very neat solution!


  • 0
    W

    how to check negative numbers? it seems this doesn't work


  • 0
    T

    Overflow doesn't mean it is negative number. It depends on how much you overflow.


  • 0
    9

    would this be considered wrong since we cannot use extra space? Wouldn't an int be considered extra space?


  • 0
    Y

    @hln9319 I think it can not solve the problem when the data id overflow.


  • 0
    P

    @yomin we do not have to consider overflow, because when it is overflow, palindromeX !=inputX


Log in to reply
 

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