-
Notifications
You must be signed in to change notification settings - Fork 2
/
palindrome_number.cc
66 lines (62 loc) · 1.47 KB
/
palindrome_number.cc
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
55
56
57
58
59
60
61
62
63
64
65
66
// Determine whether an integer is a palindrome.
// Do this without extra space.
/**
* I will add some comments later.
*/
// iterative solution
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) {
return false;
}
int divider = 1;
while (x / divider >= 10) {
divider *= 10;
}
int l = x;
int u = x;
while (l && u) {
if (u / divider != l % 10) {
return false;
}
l = (l - l % 10) / 10;
u = u - (divider * (u / divider));
divider /= 10;
}
return true;
}
};
// recursive solution. but like a shit...
class Solution {
public:
bool isPalindrome(int x) {
int i = 10;
if (x < 0) {
return false;
}
if (x >= 0 && x < 10) {
return true;
}
int divider = 1;
while (x / divider >= 10) {
divider *= 10;
}
int temp = (x - (divider * (x / divider)) - x % 10) / 10;
if (x / divider != x % 10) {
return false;
}
else {
while (temp && temp % 10 == 0) {
if (x % divider == x % (divider/i)) {
temp = temp / 10;
i = i * 10;
}
else {
return false;
}
}
return isPalindrome(temp);
}
}
};