LeetCode 9. Palindrome Number
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?
题目解析:
给定一个整数判断是否是回文,即从前往后和从后往前都是同一个数字。
思路:
依次从最高位和最低位取数字,然后判断是否相等,从两头往中间靠拢。一个数字的最低位比较好获得,即x%10即可,关键是怎么获取最高位的数字,最高位需要当前整数除以同等长度的10的倍数的数值获取到,即如果x=1234,如果想获取最高位的1,需要1234/1000得到。具体代码如下。
[cc lang=”C++”]
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0)
return false;
int d = 1;
while(x / d >= 10)
d *= 10;
while(x > 0)
{
int q = x / d;//商 最高位
int r = x % 10;//余数 最低位
if(q != r )
return false;
x = x % d / 10;//去掉最高位和最低位后的数值
d /= 100;//数值比原来数值少了两位
}
return true;
}
};
[/cc]
执行结果:

思路2:
对x的后一半内容进行反转,然后判断与前一半是否相等(x的长度为偶数)或者10倍关系(x长度为奇数)。
具体代码如下:
[cc lang=”C++”]
class Solution {
public:
bool isPalindrome(int x) {
if(x<0|| (x!=0 &&x%10==0)) return false;
int sum=0;
while(x>sum)
{
sum = sum*10+x%10;
x = x/10;
}
return (x==sum)||(x==sum/10);
}
};
[/cc]
令x=12321.初始sum=0,x=12321,
具体执行过程如下:
[table id=4 /]