题目:
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?
这道题非常简单,需要判断一个整数是否是回文数,即正着读和倒着读的结果是一样的。并且根据Example2,所有的负数应该都不是回文数,因此可以直接简单粗暴地把所有负数都return false。
首先想到的最简单的方法应该就是把数字转换成string,然后对这个string进行reverse的操作,判断reverse前后是否相同即可。这种方法可以直接采用自带的函数完成,就不写了。
如果只采用数字进行操作,那么这和昨天的reverse integer也有点相似。我最初的想法非常简单,就是建立两个指针分别指向数字的头和尾,比较这两个指针指向的数字是否相同,但是这种方法在获取这两个数字的时候有点麻烦,调试了一阵子才写出来,主要踩的坑在于mod操作要求对整数进行操作,而pow函数返回的结果是double,因此需要强制转换一下,另外就是刚开始在获取数字长度的时候没有使用temp直接用了x,导致直接把x变成了0,接下来的所有操作都无效。代码如下,耗时88ms:
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) {
return false;
}
int len = 0;
int temp = x;
while (temp != 0) {
len++;
temp /= 10;
}
for (int i = 0; i < len / 2; i++) {
int first = (int)(x / pow(10, i)) % 10;
int last = (int)(x / pow(10, len - i - 1)) % 10;
if (first != last) {
return false;
}
}
return true;
}
};
参考discussion里的思路以后发现还有一种更简单的做法,就真的相当于reverse integer那样,但是只反转后半部分,当被反转的部分大于前面的部分时就说明已经到达了一半,这时候只需要比较前一半和后一半是否相等,或者前一半是否比后一半少了最后一位数(当原数字长度为奇数时),即除以10以后相等。但是这里也有一个坑,就是如果这个数字是非0但是以0结尾的,那么这个数字肯定不是回文数,但是如果按“除以10以后相等”的评判标准,则会被判为回文数,因此需要提前排除。代码如下,耗时96ms:
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0 || (x != 0 && x % 10 == 0)) {
return false;
}
int half = 0;
while (x > half) {
half = half * 10 + x % 10;
x = x / 10;
}
cout << half << " " << x << endl;
return (half == x) || (half / 10 == x);
}
};