Skip to content

Commit 4b7fa2a

Browse files
committed
Add solution 009
1 parent 9f40957 commit 4b7fa2a

File tree

4 files changed

+63
-0
lines changed

4 files changed

+63
-0
lines changed

.gitignore

Whitespace-only changes.

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ Complete solutions to Leetcode problems, updated daily.
2121
|---|---|---|
2222
| 001 | [Two Sum](https://github.com/doocs/leetcode/tree/master/solution/001.Two%20Sum) | `Array`, `Hash Table` |
2323
| 007 | [Reverse Integer](https://github.com/doocs/leetcode/tree/master/solution/007.Reverse%20Integer) | `Math` |
24+
| 009 | [Palindrome Number](https://github.com/doocs/leetcode/tree/master/solution/009.Palindrome%20Number) | `Math` |
2425
| 013 | [Roman to Integer](https://github.com/doocs/leetcode/tree/master/solution/013.Roman%20to%20Integer) | `Math`, `String` |
2526
| 014 | [Longest Common Prefix](https://github.com/doocs/leetcode/tree/master/solution/014.Longest%20Common%20Prefix) | `String` |
2627
| 020 | [Valid Parentheses](https://github.com/doocs/leetcode/tree/master/solution/020.Valid%20Parentheses) | `String`, `Stack` |
+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
## 回文数
2+
### 题目描述
3+
4+
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
5+
6+
**示例 1:**
7+
```
8+
输入: 121
9+
输出: true
10+
```
11+
12+
**示例 2:**
13+
```
14+
输入: -121
15+
输出: false
16+
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
17+
```
18+
19+
**示例 3:**
20+
```
21+
输入: 10
22+
输出: false
23+
解释: 从右向左读, 为 01 。因此它不是一个回文数。
24+
```
25+
26+
**进阶:**
27+
28+
你能不将整数转为字符串来解决这个问题吗?
29+
30+
### 解法
31+
负数直接返回 false。对于非负数,每次取最后一位`y % 10`,累加到 `res * 10`,之后 `y /= 10`,直到 `y == 0`。判断此时 res 与 x 是否相等。
32+
33+
```java
34+
class Solution {
35+
public boolean isPalindrome(int x) {
36+
if (x < 0) {
37+
return false;
38+
}
39+
int res = 0;
40+
int y = x;
41+
while (y != 0) {
42+
res = res * 10 + y % 10;
43+
y /= 10;
44+
}
45+
return res == x;
46+
}
47+
}
48+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution {
2+
public boolean isPalindrome(int x) {
3+
if (x < 0) {
4+
return false;
5+
}
6+
int res = 0;
7+
int y = x;
8+
while (y != 0) {
9+
res = res * 10 + y % 10;
10+
y /= 10;
11+
}
12+
return res == x;
13+
}
14+
}

0 commit comments

Comments
 (0)