Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
palindrome-number.cpp 1.17 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2019-01-16 21:38 +08:00 . Update palindrome-number.cpp
// Time: O(logx) = O(1)
// Space: O(1)
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) {
return false;
}
int temp = x;
int reversed = 0;
while (temp != 0) {
if (isOverflow(reversed, temp % 10)) {
return false;
}
reversed = reversed * 10 + temp % 10;
temp = temp / 10;
}
return reversed == x;
}
private:
bool isOverflow(int q, int r) {
static const int max_q = numeric_limits<int>::max() / 10;
static const int max_r = numeric_limits<int>::max() % 10;
return (q > max_q) || (q == max_q && r > max_r);
}
};
// Time: O(logx) = O(1)
// Space: O(1)
class Solution2 {
public:
bool isPalindrome(int x) {
if(x < 0) {
return false;
}
int divisor = 1;
while (x / divisor >= 10) {
divisor *= 10;
}
for (; x > 0; x = (x % divisor) / 10, divisor /= 100) {
int left = x / divisor;
int right = x % 10;
if (left != right) {
return false;
}
}
return true;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助