Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ca6a7a4

Browse files
authored
Add files via upload
1 parent 2ae50a5 commit ca6a7a4

File tree

1 file changed

+104
-0
lines changed

1 file changed

+104
-0
lines changed

‎9、回文数.md

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
# 9、回文数
2+
3+
给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
4+
5+
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。
6+
7+
8+
9+
示例 1:
10+
11+
```
12+
输入:x = 121
13+
输出:true
14+
```
15+
16+
17+
示例 2:
18+
19+
```
20+
输入:x = -121
21+
输出:false
22+
解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
23+
```
24+
25+
26+
示例 3:
27+
28+
```
29+
输入:x = 10
30+
输出:false
31+
解释:从右向左读, 为 01 。因此它不是一个回文数。
32+
```
33+
34+
35+
示例 4:
36+
37+
```
38+
输入:x = -101
39+
输出:false
40+
```
41+
42+
43+
提示:
44+
45+
-231 <= x <= 231 - 1
46+
47+
来源:力扣(LeetCode)
48+
链接:https://leetcode-cn.com/problems/palindrome-number
49+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
50+
51+
java实现
52+
53+
```java
54+
class Solution {
55+
// 特殊情况:
56+
// 如上所述,当 x < 0 时,x 不是回文数。
57+
// 同样地,如果数字的最后一位是 0,为了使该数字为回文,
58+
// 则其第一位数字也应该是 0
59+
// 只有 0 满足这一属性
60+
61+
62+
public boolean isPalindrome(int x) {
63+
int revertNum = 0;
64+
if(x==0||(x<10&&x>0)){
65+
return true;
66+
}else if(x<0||x%10==0){
67+
return false;
68+
}else{
69+
// 当数字长度为奇数时,我们可以通过 revertedNumber/10 去除处于中位的数字。
70+
// 例如,当输入为 12321 时,在 while 循环的末尾我们可以得到 x = 12,revertedNumber = 123,
71+
// 由于处于中位的数字不影响回文(它总是与自己相等),所以我们可以简单地将其去除。
72+
73+
74+
while(x>revertNum){
75+
revertNum = revertNum*10+x%10;
76+
x/=10;
77+
}
78+
79+
}
80+
return revertNum==x||(revertNum/10)==x;
81+
}
82+
}
83+
```
84+
85+
c语言实现
86+
87+
```c
88+
bool isPalindrome(int x){
89+
int revertNum = 0;
90+
if(x==0||(x<10&&x>0)){
91+
return true;
92+
}else if(x<0||x%10==0){
93+
return false;
94+
}else{
95+
while(x>revertNum){
96+
revertNum = revertNum*10+x%10;
97+
x/=10;
98+
}
99+
100+
}
101+
return revertNum==x||(revertNum/10)==x;
102+
}
103+
```
104+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /