# [LeetCode] 9. Palindrome Number 验证回文数字

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true


Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.


Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.


Coud you solve it without converting the integer to a string?

class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) return false;
int div = 1;
while (x / div >= 10) div *= 10;
while (x > 0) {
int left = x / div;
int right = x % 10;
if (left != right) return false;
x = (x % div) / 10;
div /= 100;
}
return true;
}
};

class Solution {
public:
bool isPalindrome(int x) {
if (x < 0 || (x % 10 == 0 && x != 0)) return false;
int revertNum = 0;
while (x > revertNum) {
revertNum = revertNum * 10 + x % 10;
x /= 10;
}
return x == revertNum || x == revertNum / 10;
}
};

class Solution {
public:
bool isPalindrome(int x) {
if (x < 0 || (x % 10 == 0 && x != 0)) return false;
return reverse(x) == x;
}
int reverse(int x) {
int res = 0;
while (x != 0) {
if (res > INT_MAX / 10) return -1;
res = res * 10 + x % 10;
x /= 10;
}
return res;
}
};

Github 同步地址：

https://github.com/grandyang/leetcode/issues/9

Reverse Integer

https://leetcode.com/problems/palindrome-number/

https://leetcode.com/problems/palindrome-number/discuss/5127/9-line-accepted-Java-code-without-the-need-of-handling-overflow

LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2014-11-27 02:28  Grandyang  阅读(21223)  评论(7编辑  收藏  举报