forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpalindrome-number.cpp
More file actions
44 lines (39 loc) · 863 Bytes
/
palindrome-number.cpp
File metadata and controls
44 lines (39 loc) · 863 Bytes
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
// 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) {
reversed = reversed * 10 + temp % 10;
temp = temp / 10;
}
return reversed == x;
}
};
// 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;
}
};