Skip to content

Commit 62fdfbb

Browse files
author
henryjia
committed
📚faq
1 parent ae0dea0 commit 62fdfbb

19 files changed

Lines changed: 467 additions & 157 deletions

File tree

‎docs/.DS_Store‎

0 Bytes
Binary file not shown.

‎docs/_images/.DS_Store‎

0 Bytes
Binary file not shown.

‎docs/_images/java/.DS_Store‎

0 Bytes
Binary file not shown.
622 KB
Loading

‎docs/_images/java/JVM/oom-end.png‎

170 KB
Loading
18.1 KB
Loading
22.4 KB
Loading
0 Bytes
Binary file not shown.
0 Bytes
Binary file not shown.
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
### [9. 回文数](https://leetcode.cn/problems/palindrome-number/)
2+
3+
> 给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
4+
>
5+
> 回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
6+
>
7+
> 例如,121 是回文,而 123 不是。
8+
>
9+
10+
**思路**:
11+
12+
解法1:转成字符串后反转并比较
13+
14+
```java
15+
public boolean isPalindrome(int num){
16+
String revertNum = new StringBuilder(""+num).reverse().toString();
17+
return revertNum.equals(num+"");
18+
}
19+
```
20+
21+
解法2:反转一半数字(数学法)
22+
23+
例如,输入 1221,我们可以将数字 “1221” 的后半部分从 “21” 反转为 “12”,并将其与前半部分 “12” 进行比较,因为二者相同,我们得知数字 1221 是回文。
24+
25+
![fig1](https://tva1.sinaimg.cn/large/e6c9d24ely1h35m91kil7j20zk0k00uc.jpg)
26+
27+
1. 每次进行取余操作 ( %10),取出最低的数字:y = x % 10
28+
2. 将最低的数字加到取出数的末尾:revertNum = revertNum * 10 + y
29+
3. 每取一个最低位数字,x 都要自除以 10
30+
4. 判断 x 是不是小于 revertNum ,当它小于的时候,说明数字已经对半或者过半了
31+
5. 最后,判断奇偶数情况:如果是偶数的话,revertNum 和 x 相等;如果是奇数的话,最中间的数字就在revertNum 的最低位上,将它除以 10 以后应该和 x 相等。
32+
33+
```java
34+
public boolean isPalindrome(int num){
35+
//所有负数、所有大于 0 且个位是 0 的数字都不可能是回文
36+
if(num < 0 || (num > 0 && num % 10 == 0)){
37+
return false;
38+
}
39+
int tmp = 0;
40+
while(num > tmp){
41+
tmp = tmp * 10 + tmp % 10;
42+
num = num / 10;
43+
}
44+
return num == tmp || num == tmp / 10;
45+
}
46+
```
47+

0 commit comments

Comments
 (0)