forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpalindrome-number.cpp
54 lines (48 loc) · 1.17 KB
/
palindrome-number.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// 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;
}
};