-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path007_Reverse_Integer.java
70 lines (56 loc) · 1.64 KB
/
007_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
class Solution {
public int reverse(int x) {
if (x == 0) return 0;
long res = 0;
while (x != 0) {
res = res * 10 + x % 10;
if (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE)
return 0;
x /= 10;
}
return (int) res;
}
}
******************************************************************************
class Solution {
public int reverse(int x) {
int result = 0;
int reminder = x;
while (reminder != 0) {
int lastDigit = reminder % 10;
int nextRes = result * 10 + lastDigit;
/*
expression '(nextRes - lastDigit) / 10' should return us the current result
if it's different - it means that we have an int overflow
*/
if ((nextRes - lastDigit) / 10 != result) {
return 0;
}
result = nextRes;
reminder /= 10;
}
return result;
}
}
************************************************************************
class Solution {
public int reverse(int x) {
boolean isNegative = x<0;
if(isNegative){
x=x*-1;
}
long newNumber = 0;
while(x>0){
int lastDigitOfX = x%10;
newNumber = (newNumber*10) + lastDigitOfX;
x = x/10;
}
if(newNumber > Integer.MAX_VALUE){
return 0;
}
if(isNegative){
newNumber = newNumber*-1;
}
return (int)newNumber;
}
}