判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例 1:
输入: 121 输出: true
示例 2:
输入: -121 输出: false 解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入: 10 输出: false 解释: 从右向左读, 为 01 。因此它不是一个回文数。
进阶:
你能不将整数转为字符串来解决这个问题吗?
先说不用转字符串的办法:
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
else:
s = str(x)
new_s = s[::-1]
if x == int(new_s):
return True
else: return False
一次就过了……
网上更简单的写法,要返回的都在return那行,简直了:
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
return str(x)==str(x)[::-1]
在网上看了不转化成字符串的方法,从纯数学的角度去看就是,a=10^(n-1) * a1 + 10^(n-2) * a2 + ……+ 10^0 * an (n是位数)。所以把每一位逆转过来乘10的对应次方就好了。用一个简单循环解决:
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
else:
ans = self.palin(x)
if ans == x:
return True
else:
return False
def palin(self, y):
ans = 0
while(y!=0):
ans = ans * 10 + (y % 10)
y = int(y/10)
return ans
谈不上多巧妙,但是是从本质上理解这个问题。Mark!