给你一个整数 x
,如果 x
是一个回文整数,返回 true
;否则,返回 false
。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
- 例如,
121
是回文,而123
不是。
示例 1:
输入:x = 121
输出:true
示例 2:
输入:x = -121
输出:false
解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
class Solution {
public:
bool isPalindrome(int x) {
// 边界判定
if (x < 0 || x % 10 == 0 && x != 0) return false;
if (x >= 0 && x < 10) return true;
int x0 = x;
int y = 0;
int n;
while (x != 0) {
n = x % 10;
if (y > INT_MAX / 10) return false;
y = y * 10 + n;
x /= 10;
}
return true ? (x0 == y) : false;
}
}
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0 || x % 10 == 0 && x != 0) return false;
if (x >= 0 && x < 10) return true;
int x0 = x;
char s[32]; // 顶多32位,再多就越界了
int i = 0; // 可以用动态数组vector,但是会慢很多
// convert to string
while (x != 0) {
s[i] = x % 10 + '0';
x /= 10;
i++;
}
int pre = 0, end = i - 1;
while (pre <= end) {
if (s[pre] != s[end]) return false;
else {
pre++;
end--;
}
}
return true;
}
}
由于整个过程我们不断将原始数字除以 10,然后给反转后的数字乘上 10,所以,当原始数字小于或等于反转后的数字时,就意味着我们已经处理了一半位数的数字了。
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0 || x % 10 == 0 && x != 0) return false;
if (x >= 0 && x < 10) return true;
//
int revertedNumber = 0;
while (x > revertedNumber) {
revertedNumber = x % 10 + reverted * 10;
x /= 10;
}
return x == revertedNumber || x == revertedNumber / 10;
}
}
LeetCode 9.回文数