蜗牛慢慢爬 LeetCode 9. Palindrome Number [Difficulty: Easy]

题目

Determine whether an integer is a palindrome. Do this without extra space.

Some hints:
Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

翻译

判断数字是否是回文的 不能使用额外空间

Hints

Related Topics: Math
不能转换成字符串 也不要用数字倒置(leetcode 7)
可以利用数字倒置时用到的方法

代码

Java

class Solution {
    public boolean isPalindrome(int x) {
        if (x<0 || (x!=0 && x%10==0)) return false;
        int result = 0;
        while (x>result){
        	result = result*10 + x%10;
        	x = x/10;
        }
        return (x==result || x==result/10);
    }
}

Python

class Solution(object):
    def isPalindrome(self, x):
        if x<0 or (x!=0 and x%10==0):
            return False
        result = 0
        while x>result:
            result = result*10 + x%10
            x = x/10
        return (x==result or x==result/10)
                
posted @ 2017-09-05 20:52  cookielbsc  阅读(126)  评论(0编辑  收藏  举报