-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP0007_ReverseInteger.java
More file actions
104 lines (97 loc) · 3.18 KB
/
P0007_ReverseInteger.java
File metadata and controls
104 lines (97 loc) · 3.18 KB
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
package yyl.leetcode.p00;
/**
* <h3>整数反转</h3> <br>
* 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。<br>
* 示例 1:<br>
* 输入: 123<br>
* 输出: 321<br>
* 示例 2:<br>
* 输入: -123<br>
* 输出: -321<br>
* 示例 3:<br>
* 输入: 120<br>
* 输出: 21<br>
* 注意:<br>
* 假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。 请根据这个假设,如果反转后整数溢出那么就返回 0。<br>
* <br>
* Reverse digits of an integer.<br>
* Example1: x = 123, return 321 <br>
* Example2: x = -123, return -321 <br>
* Note:<br>
* The input is assumed to be a 32-bit signed integer. <br>
* Your function should return 0 when the reversed integer overflows.<br>
*/
public class P0007_ReverseInteger {
public static void main(String[] args) {
Solution solution = new Solution();
int[] samples = {0, 123, -2147483648, -100, -123, 2147447412, 1534236469, -2147483412};
for (int sample : samples) {
System.out.println(sample + " -> " + solution.reverse(sample));
}
}
static class Solution {
public int reverse(int x) {
long reverse = 0;
while (x != 0) {
reverse = (reverse * 10) + (x % 10);
x /= 10;
}
// overflows
if (reverse > Integer.MAX_VALUE || reverse < Integer.MIN_VALUE) {
return 0;
}
return (int) reverse;
}
}
static class Solution2 {
public int reverse(int x) {
int result = 0;
while (x != 0) {
int digit = x % 10;
int forward = result * 10 + digit;
// overflows
if ((forward - digit) / 10 != result) {
return 0;
}
result = forward;
x /= 10;
}
return result;
}
}
static class Solution3 {
public int reverse(int x) {
// MIN_VALUE -2147483648
// MAX_VALUE +2147483647
if (x == Integer.MIN_VALUE || x == Integer.MAX_VALUE) {
return 0;
}
boolean negative = x < 0;
if (negative) {
x = -x;
}
int[] digits = new int[10];
int n = 0;
int d = x;
while (d != 0) {
digits[n++] = d % 10;
d /= 10;
}
int limit = negative ? Integer.MIN_VALUE : -Integer.MAX_VALUE;
int multiLimit = limit / 10;
int result = 0;
for (int i = 0; i < n; i++) {
if (result < multiLimit) {
return 0;// overflows
}
result *= 10;
int digit = digits[i];
if (result < limit + digit) {
return 0;// overflows
}
result -= digit;
}
return negative ? result : -result;
}
}
}