Skip to content

Commit e5b79a8

Browse files
committed
Update solution 007
1 parent e7e9c79 commit e5b79a8

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

solution/007.Reverse Integer/README.md

+22
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@
2626
假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231, 231 − 1]。根据这个假设,如果反转后的整数溢出,则返回 0。
2727

2828
### 解法
29+
- 解法1:
30+
2931
用 long 型存储该整数,取绝对值,然后转成 StringBuilder 进行 reverse,后转回 int。注意判断该数是否在[Integer.MIN_VALUE, Intger.MAX_VALUE] 范围内。
3032

3133
```java
@@ -48,4 +50,24 @@ class Solution {
4850

4951
}
5052
}
53+
```
54+
55+
- 解法2:
56+
57+
循环对数字求 `%, /` ,累加,最后返回结果。注意判断值是否溢出。
58+
```java
59+
class Solution {
60+
public int reverse(int x) {
61+
long res = 0;
62+
// 考虑负数情况,所以这里条件为: x != 0
63+
while (x != 0) {
64+
res = res * 10 + (x % 10);
65+
x /= 10;
66+
}
67+
return (res < Integer.MIN_VALUE || res > Integer.MAX_VALUE)
68+
? 0
69+
: (int) res;
70+
71+
}
72+
}
5173
```

solution/007.Reverse Integer/Solution.java

+17
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
/*
12
class Solution {
23
public int reverse(int x) {
34
if (x == 0) {
@@ -15,5 +16,21 @@ public int reverse(int x) {
1516
1617
return isPositive ? (val > Integer.MAX_VALUE ? 0 : (int) val) : (-val < Integer.MIN_VALUE ? 0 : (int) (-val));
1718
19+
}
20+
}
21+
*/
22+
23+
class Solution {
24+
public int reverse(int x) {
25+
long res = 0;
26+
// 考虑负数情况,所以这里条件为: x != 0
27+
while (x != 0) {
28+
res = res * 10 + (x % 10);
29+
x /= 10;
30+
}
31+
return (res < Integer.MIN_VALUE || res > Integer.MAX_VALUE)
32+
? 0
33+
: (int) res;
34+
1835
}
1936
}

0 commit comments

Comments
 (0)