9. Palindrome Number
- 回文数字
题目
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
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.
思路
回文数字:
- 非负数
- 倒置后数字一致
复杂性分析:
- 时间复杂度:O(n).
- 空间复杂度:O(1).
题解
class Solution {
public:
bool isPalindrome(int x) {
int x_temp = x, x_mirror = 0;
while (x_temp > 0) {
x_mirror = x_mirror*10 + x_temp%10;
x_temp /= 10;
}
if (x_mirror == x) return true;
return false;
}
};