Palindrome Number

9.Palindrome Number

Given an integer x, return true if x is palindrome integer.

An integer is a palindrome when it reads the same backward as forward.

Example 1:

1
2
3
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.

Example 2:

1
2
3
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

个人解答:

时间复杂度:O(n)

空间复杂度:O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
bool isPalindrome(int x) {
if(x < 0)return false;
int count = 0;//x位数
int temp = x;
while (temp != 0) {
temp /= 10;
count++;
}
int first = pow(10, count-1);//选中首位时所需除数
count /= 2;//只需遍历数字一半
while (count--) {
if (x / first != x % 10)return false;
else {
x %= first;
x /= 10;
first /= 100;
}
}
return true;
}
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
#include <iostream>
#include <string>
#include <iomanip>

using namespace std;


class Solution {

public:
bool is_palindrome(int value) {
if (value < 0) return false;
if (value < 10) return true;
int divdend = 1;
while (divdend < value) {
divdend *= 10;
}
divdend /= 10;
while (value != 0) {
int first = value / divdend;
int last = value % 10;
if (first != last) return false;
value = (value % divdend) / 10;
divdend /= 100;
}
return true;
}
bool is_palindrome_str(int value) {
if (value < 0) return false;
string s = to_string(value);
string backup = s;
reverse(begin(s), end(s));
return s == backup;
}
};

int main(int argc, char* argv[]) {
int value;
Solution sol;
while (cin >> value) {
cout << value << " is palindrome: " << boolalpha << sol.is_palindrome_str(value) << endl;
}
return EXIT_SUCCESS;
}