[LeetCode] 9. Palindrome Number
题目链接:传送门
Description
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.
Solution
题意:
判断一个数是否回文(忽略空格)
思路:
去掉负数的情况,其他的情况保存一下每个位置上的数,按照判回文的方法直接判即可
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) return false;
vector<int> nums;
while (x) {
nums.push_back(x % 10);
x /= 10;
}
int s = nums.size();
for (int i = 0; i < s / 2; i++) {
if (nums[i] != nums[s - 1 - i]) return false;
}
return true;
}
};
官方Solution:
思路其实差不多,但是在实现上的技巧更赞,贴一下贴一下
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0 || (x != 0 && x % 10 == 0)) return false;
int revertNumber = 0;
while (x > revertNumber) {
revertNumber = revertNumber * 10 + x % 10;
x /= 10;
}
return x == revertNumber || x == revertNumber / 10;
}
};