-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseInteger.java
More file actions
52 lines (47 loc) · 1.19 KB
/
ReverseInteger.java
File metadata and controls
52 lines (47 loc) · 1.19 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
package easy;
/**
* Given a 32-bit signed integer, reverse digits of an integer.
* <p>
* 给定一个 32 位有符号整数,将整数中的数字进行反转。
* <p>
* Created by kaming on 2018/7/12.
*/
public class ReverseInteger {
/**
* Example 1:
*
* Input: 123
* Output: 321
*
* Example 2:
*
* Input: -123
* Output: -321
*
* Example 3:
*
* Input: 120
* Output: 21
*
*/
public static void main(String[] args){
int exp1 = reverse(123);
System.out.println(exp1);
int exp2 = reverse(-123);
System.out.println(exp2);
int exp3 = reverse(120);
System.out.println(exp3);
}
private static int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
//assume that your function returns 0 when the reversed integer overflows
if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
}