-
Notifications
You must be signed in to change notification settings - Fork 0
/
0007.Reverse-Integer.java
111 lines (106 loc) · 2.53 KB
/
0007.Reverse-Integer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
* @lc app=leetcode id=7 lang=java
*
* [7] Reverse Integer
*
* https://leetcode.com/problems/reverse-integer/description/
*
* algorithms
* Easy (26.07%)
* Likes: 5165
* Dislikes: 7786
* Total Accepted: 1.6M
* Total Submissions: 6.3M
* Testcase Example: '123'
*
* Given a signed 32-bit integer x, return x with its digits reversed. If
* reversing x causes the value to go outside the signed 32-bit integer range
* [-2^31, 2^31 - 1], then return 0.
*
* Assume the environment does not allow you to store 64-bit integers (signed
* or unsigned).
*
*
* Example 1:
* Input: x = 123
* Output: 321
* Example 2:
* Input: x = -123
* Output: -321
* Example 3:
* Input: x = 120
* Output: 21
* Example 4:
* Input: x = 0
* Output: 0
*
*
* Constraints:
*
*
* -2^31 <= x <= 2^31 - 1
*
*
*/
class Solution {
public int reverse(int x) {
int ans = 0;
while (x != 0) {
// take the last number
int tail = x % 10;
// if ans > MAX_VALUE / 10, there is still tail to add,so memory overflows
// if ans == MAX_VALUE / 10, and tail > 7 ,it memory overflows, because 7 is digits of 2 ^ 31 - 1
if (ans > Integer.MAX_VALUE / 10 || (ans == Integer.MAX_VALUE / 10 && tail > 7)) {
return 0;
}
// if ans < Min_VALUE / 10, there is still tail to add, so memory overflows
// if ans == MIN_VALUE / 10, and tail < -8,it memory overflows, because -8 is digits of -2 ^ 31
if (ans < Integer.MIN_VALUE / 10 || (ans == Integer.MIN_VALUE / 10 && tail < - 8)) {
return 0;
}
ans = ans * 10 + tail;
x /= 10;
}
return ans;
}
public int reverse1(int x) {
int result = 0;
while (x != 0) {
int tail = x % 10;
int last = result * 10 + tail;
if (last / 10 != result) {
return 0;
}
result = last;
x /= 10;
}
return result;
}
public int reverse2(int x) {
int sign = x > 0 ? 1 : -1;
x = x > 0 ? x : -x;
int result = 0;
while (x > 0) {
if (Integer.MAX_VALUE / 10 < result || (Integer.MAX_VALUE - x % 10) < result * 10) {
return 0;
}
result = result * 10 + x % 10;
x /= 10;
}
return sign * result;
}
public int reverse3(int x){
int result = 0;
while (x != 0) {
int tail;
tail = x % 10;
// greater than the max or less than the min will overflow
if (Integer.MAX_VALUE / 10 < result || Integer.MIN_VALUE / 10 > result) {
return 0;
}
result = result * 10 + tail;
x /= 10;
}
return result;
}
}