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.
每次区首尾两位进行比较,然后再去掉首尾两位循环。
#include <iostream> #include <vector> #include <set> #include <algorithm> #include <string> #include <sstream> #include <cstring> #include <cmath> using namespace std; class Solution { public: bool isPalindrome(int x) { if (x < 0) { return false; } //数字长度 int len = 0; int temp = x; while(temp != 0) { temp = temp / 10; len++; } while(x != 0) { int bottom = x % 10; int top = x / (int)pow(10, len - 1); if (bottom != top) { return false; } x = (x % (int)pow(10, len - 1)) / 10; len -= 2; } return true; } }; int main() { Solution s; cout << s.isPalindrome(123212) << endl; return 0; }