-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path回文数.cpp
88 lines (77 loc) · 1.44 KB
/
回文数.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
bool isPalindrome(int x)
{
string s = to_string(x);
int left = 0, right = s.size() - 1;
while (left < right)
{
if (s[left] == s[right])
{
++left;
--right;
}
else
return false;
}
return true;
}
// 这是进阶版,不将整数转化为string
// 将整数翻转一半来进行比较
bool isPalindrome_1(int x)
{
// 负数或者最后一位为0,都是false
if (x < 0 || (x != 0 && x % 10 == 0))
return false;
int revertedNumber = 0;
// 当反转后的数字大于x时,说明已经反转了一半了
while (revertedNumber < x)
{
revertedNumber = revertedNumber * 10 + x % 10;
x /= 10;
}
return x == revertedNumber || x == revertedNumber / 10;
}
//update 2019.3.1
bool isPalindrome2(int x)
{
if (x<0||(x!=0&&x%10==0))
return false;
int num=0;
while (x>num)
{
int digit = x%10;
num = num*10+digit;
x /= 10;
}
return (num==x || num /10 == x);
}
//update 2019.9.23
bool isPalindrome3(int x)
{
if (x < 0 || (x != 0 && x % 10 == 0))
return false;
if (x >= 0 && x < 10)
return true;
int res = 0;
while (x>res)
{
int tmp = x % 10;
res = res * 10 + tmp;
x = x / 10;
if (res == x || res == x / 10)
return true;
}
return false;
}
};
int main()
{
Solution a;
cout << a.isPalindrome_1(121) << endl;
system("pause");
}