【LeetCode with Python】 Palindrome Number

来源:互联网 发布:ye2系列电机绕组数据书 编辑:程序博客网 时间:2024/05/20 15:37
博客域名:http://www.xnerv.wang
原题页面:https://oj.leetcode.com/problems/palindrome-number/
题目类型:
难度评价:★
本文地址:http://blog.csdn.net/nerv3x3/article/details/37335981

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

click to show spoilers.

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.


class Solution:    # @return a boolean    def isPalindrome(self, x):        if x < 0:            return False        if x < 10:            return True        div = 1        val = x        while True:            val = int(val / 10)            if val > 0:                div *= 10            else:                break        while div > 0:            left = int(x / div)            right = int(x % 10)            if left != right:                return False            x = x % div            x = x / 10            div = int(div / 100)        return True

0 0