File tree 2 files changed +39
-0
lines changed
solution/007.Reverse Integer
2 files changed +39
-0
lines changed Original file line number Diff line number Diff line change 26
26
假设我们的环境只能存储 32 位有符号整数,其数值范围是 [ −231, 231 − 1] 。根据这个假设,如果反转后的整数溢出,则返回 0。
27
27
28
28
### 解法
29
+ - 解法1:
30
+
29
31
用 long 型存储该整数,取绝对值,然后转成 StringBuilder 进行 reverse,后转回 int。注意判断该数是否在[ Integer.MIN_VALUE, Intger.MAX_VALUE] 范围内。
30
32
31
33
``` java
@@ -48,4 +50,24 @@ class Solution {
48
50
49
51
}
50
52
}
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
+ }
51
73
```
Original file line number Diff line number Diff line change
1
+ /*
1
2
class Solution {
2
3
public int reverse(int x) {
3
4
if (x == 0) {
@@ -15,5 +16,21 @@ public int reverse(int x) {
15
16
16
17
return isPositive ? (val > Integer.MAX_VALUE ? 0 : (int) val) : (-val < Integer.MIN_VALUE ? 0 : (int) (-val));
17
18
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
+
18
35
}
19
36
}
You can’t perform that action at this time.
0 commit comments