【leetcode】Palindrome Number

题目简述:

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.

解题思路:

首先最简单的就是想到直接转成字符串最前一个和最后一个比较,而且做出来效果还不错。不过题目说可以直接操作数字,那么我们也可以想办法每次取出数字的最高位和最低位进行比较,办法就是用一个base取最高位,每次取后base/100

class Solution:
# @return a boolean
def isPalindrome(self, x):
if x < 0:
return False
else:
s = str(x)
l = len(s)
for i in range(l/2):
if s[i] != s[l-i-1]:
return False
return True class Solution:
# @return a boolean
def isPalindrome(self, x):
if x < 0:
return False
base = 1
while x / base >= 10:
base *= 10
while x > 0:
left = x / base
right = x % 10
if left != right:
return False
x -= base * left
x /= 10
base /= 100
return True
上一篇:用mp3stego来加密与解密文件的几次尝试


下一篇:九度 题目1437:To Fill or Not to Fill