题干:

难度:Easy

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true

Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Follow up:
Coud you solve it without converting the integer to a string?

解析:

判断一个整数是否是回文,进阶要求是不把数字转为字符串判断。我们可以利用整数反转的方法来比较数字,比较到数字位数长度的一半即可,提前剔除数字小于0和为10的倍数这两种一定不是回文的特殊情况.

Java解法

class Solution {
    public boolean isPalindrome(int x) {
        //负数,可以被10整除的非零数都可以排除
        if(x<0||(x!=0&&x%10==0))
            return false;
        //利用倒置整数的思想,比较一半空间即可
        int hreverse=0;
        while(x>hreverse){
            hreverse=hreverse*10+x%10;
            x=x/10;
        }
        return x==hreverse||hreverse/10==x?true:false;
    }
}

Python解法

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x<0 or x!=0 and x%10==0:
            return False
        #用倒置整数的方法比较一半即可
        hreverse=0
        while x>hreverse:
            hreverse=hreverse*10+x%10
            x=x//10
        return True if x==hreverse or hreverse//10==x else False
最后修改:2020 年 02 月 07 日 09 : 36 AM