Problem:
Determine whether an integer is a palindrome. Do this without extra space.
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
分析:
回文问题也是经典的面试算法问题。此题是判断int是否是回文,有如下思路:
1、将int转换为string,再判断。
这是最常用的方法,转换后可二分比较,但需要额外空间
2、先将int翻转,再比较两数,翻转方法参见:[C++]LeetCode 7:Reverse Integer(翻转整数)
翻转时考虑了溢出情况,此题中需要另行考虑溢出。
3、直接需要最高和最低位进行比较。(代码采用此法)
看起来有点笨,但是比较通用。
4、期待大家提供更快捷的方法^O^
AC Code(C++):
class Solution {
public:
//11505 / 11505 test cases passed.
//Runtime: 124 ms
bool isPalindrome(int x) {
if (x < 0) return false;//负数不为回文
int leftDiv = 1;//计算左边的最大除数
for (int i = x; i > 9; i /= 10){
leftDiv *= 10;
}
int rightDiv = 10;
while (rightDiv <= leftDiv){//判断是否是回文
if (x%rightDiv != x / leftDiv){//非回文
return false;
}
else{
x = (x%leftDiv) / rightDiv;
//rightDiv *= 10;
leftDiv /= 100;
}
}
return true;
}
};