Palindrome Number
Determine whether an integer is a palindrome. Do this without extra space.
解题思路
需要注意一下几点:
1. 负数不是回文数,直接返回false。
2. 可以把整数转化成字符串,判断字符串是否是回文串。不过需要额外空间。
3. 利用在Reverse Integer中提供的方法先求出反转后的数字,然后比较是否相等。不过 reversed integer 可能会溢出。
使用 / 和 % 运算符从整数的两头依次取数字比较,向中间推进。代码如下:
class Solution {
public:
bool isPalindrome(int x) {
// 负数不是回文数
if (x < 0) return false;
// initialize how many zeros
int base = 1;
while (x / base >= 10) {
base *= 10;
}
// 使用 / 和 % 运算符从整数的两头依次取数字比较,向中间推进
while (x) {
int left = x / base; // 当前比较的最左边数字
int right = x % 10; // 当前比较的最右边数字
// 有一对数字不相等,不是回文数
if (left != right) return false;
x = (x % base) / 10; // x % base 移除最高位;(x % base) / 10 再移除最低位
base /= 100; // 从 x 中移除了两个数位
}
return true;
}
};