Title :
Determine whether an integer is a palindrome. Do this without extra space.
思路1 : 将数字翻转,然后看是否相等。是否越界的问题,如果真是回文串是不会越界的
class Solution { public: int reverseInteger(int x){ int result = 0; while (x){ result = result * 10 + x % 10; x /= 10; } return result; } bool isPalindrome(int x) { if (x < 0) return false; int reverse = reverseInteger(x); // cout<<reverse<< " "<<x<<endl; return (reverse == x); } };
思路2:
从左右两边分别验证是否相等
class Solution { public: bool isPalindrome(int x) { if (x < 0) return false; if (x < 10) return true; int digits = 0; int t = x; int d = 0; while(t != 0) t /= 10, ++d; int left = pow(10, d - 1); int right = 1; while( left >= right) { if (x / left % 10 != x / right % 10) return false; left /= 10; right *= 10; } return true; } };