Skip to content

Commit 9dfb2a5

Browse files
committed
Update solution 007
1 parent f4b1a1b commit 9dfb2a5

File tree

3 files changed

+71
-0
lines changed

3 files changed

+71
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ Complete solutions to Leetcode problems, updated daily.
1313
| # | Title | Tags |
1414
|---|---|---|
1515
| 001 | [Two Sum](https://github.com/yanglbme/leetcode/tree/master/solution/001.Two%20Sum) | `Array`, `Hash Table` |
16+
| 007 | [Reverse Integer](https://github.com/yanglbme/leetcode/tree/master/solution/007.Reverse%20Integer) | `Math` |
1617
| 021 | [Merge Two Sorted Lists](https://github.com/yanglbme/leetcode/tree/master/solution/021.Merge%20Two%20Sorted%20Lists) | `Linked List` |
1718
| 083 | [Remove Duplicates from Sorted List](https://github.com/yanglbme/leetcode/tree/master/solution/083.Remove%20Duplicates%20from%20Sorted%20List) | `Linked List` |
1819
| 203 | [Remove Linked List Elements](https://github.com/yanglbme/leetcode/tree/master/solution/203.Remove%20Linked%20List%20Elements) | `Linked List` |
+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
## 反转整数
2+
### 题目描述
3+
4+
给定一个 32 位有符号整数,将整数中的数字进行反转。
5+
6+
示例 1:
7+
```
8+
输入: 123
9+
输出: 321
10+
```
11+
12+
示例 2:
13+
```
14+
输入: -123
15+
输出: -321
16+
```
17+
18+
示例 3:
19+
```
20+
输入: 120
21+
输出: 21
22+
```
23+
24+
注意:
25+
26+
假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231, 231 − 1]。根据这个假设,如果反转后的整数溢出,则返回 0。
27+
28+
### 解法
29+
用 long 型存储该整数,取绝对值,然后转成 StringBuilder 进行 reverse,后转回 int。注意判断该数是否在[Integer.MIN_VALUE, Intger.MAX_VALUE] 范围内。
30+
31+
```java
32+
class Solution {
33+
public int reverse(int x) {
34+
if (x == 0) {
35+
return x;
36+
}
37+
38+
long tmp = x;
39+
boolean isPositive = true;
40+
if (tmp < 0) {
41+
isPositive = false;
42+
tmp = -tmp;
43+
}
44+
45+
long val = Long.parseLong(new StringBuilder(String.valueOf(tmp)).reverse().toString());
46+
47+
return isPositive ? (val > Integer.MAX_VALUE ? 0 : (int) val) : (-val < Integer.MIN_VALUE ? 0 : (int) (-val));
48+
49+
}
50+
}
51+
```
+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
public int reverse(int x) {
3+
if (x == 0) {
4+
return x;
5+
}
6+
7+
long tmp = x;
8+
boolean isPositive = true;
9+
if (tmp < 0) {
10+
isPositive = false;
11+
tmp = -tmp;
12+
}
13+
14+
long val = Long.parseLong(new StringBuilder(String.valueOf(tmp)).reverse().toString());
15+
16+
return isPositive ? (val > Integer.MAX_VALUE ? 0 : (int) val) : (-val < Integer.MIN_VALUE ? 0 : (int) (-val));
17+
18+
}
19+
}

0 commit comments

Comments
 (0)