题目:
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?
解释:
判断一个数是否是回文。首先,负数一定不是回文。
一种朴素的想法:
1.将原数字倒置后判断是否和原数字相等,但是,倒置之后数字有可能溢出(这种方法python可用但是c++不可用)
2.双指针法,去最高位和最低位判断是否相等,如果相等则去除这两位继续判断,注意len的求法,合理使用/ 和%。
python代码:
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x<0:
return False
cur_len=1
while (x/cur_len>=10):
cur_len*=10
while x>0:
left=x/cur_len
right=x%10
if left!=right:
return False
else:
x=(x%cur_len)/10
cur_len/=100
return True
c++代码:
class Solution {
public:
bool isPalindrome(int x) {
if(x<0)
return false;
int cur_len=1;
while (x/cur_len>=10)
cur_len*=10;
while(x>0)
{
int left=x/cur_len;
int right=x%10;
if (left!=right)
return false;
else
{
x=(x%cur_len)/10;
cur_len/=100;
}
}
return true;
}
};
总结:
遇到回文的问题尽量还是不要转换成字符串做,这不是常规的做法。
c++中判断两个字符串是否相等 str1.compare(str2)==0
。