Skip to content

Commit c18bae8

Browse files
committed
solve problem Reverse Integer
1 parent 6f45671 commit c18bae8

File tree

5 files changed

+58
-0
lines changed

5 files changed

+58
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,7 @@ All solutions will be accepted!
184184
|581|[Shortest Unsorted Continuous Subarray](https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray/description/)|[java/py/js](./algorithms/ShortestUnsortedContinuousSubarray)|Easy|
185185
|443|[String Compression](https://leetcode-cn.com/problems/string-compression/description/)|[java/py/js](./algorithms/StringCompression)|Easy|
186186
|438|[Find All Anagrams In A String](https://leetcode-cn.com/problems/find-all-anagrams-in-a-string/description/)|[java/py/js](./algorithms/FindAllAnagramsInAString)|Easy|
187+
|7|[Reverse Integer](https://leetcode-cn.com/problems/reverse-integer/description/)|[java/py/js](./algorithms/ReverseInteger)|Easy|
187188

188189
# Database
189190
|#|Title|Solution|Difficulty|

algorithms/ReverseInteger/README.md

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Reverse Integer
2+
This problem is easy to solve
+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
public int reverse(int x) {
3+
int res = 0,
4+
MAX_INTEGER_BOUNDARY = Integer.MAX_VALUE / 10,
5+
MIN_INTEGER_BOUNDARY = Integer.MIN_VALUE / 10;
6+
7+
while (x != 0) {
8+
int pop = x % 10;
9+
x /= 10;
10+
11+
if (res > MAX_INTEGER_BOUNDARY || (res == MAX_INTEGER_BOUNDARY && pop > 7)) return 0;
12+
if (res < MIN_INTEGER_BOUNDARY || (res == MIN_INTEGER_BOUNDARY && pop < -8)) return 0;
13+
14+
res = res * 10 + pop;
15+
}
16+
17+
return res;
18+
}
19+
}

algorithms/ReverseInteger/solution.js

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* @param {number} x
3+
* @return {number}
4+
*/
5+
var reverse = function(x) {
6+
let res = 0,
7+
MAX_INTEGER_BOUNDARY = parseInt((Math.pow(2, 31) - 1) / 10),
8+
MIN_INTEGER_BOUNDARY = parseInt(Math.pow(-2, 31) / 10)
9+
10+
while (x != 0) {
11+
let pop = x % 10
12+
x = parseInt(x / 10)
13+
14+
if (res > MAX_INTEGER_BOUNDARY || (res === MAX_INTEGER_BOUNDARY && pop > 7)) return 0
15+
if (res < MIN_INTEGER_BOUNDARY || (res === MIN_INTEGER_BOUNDARY && pop < -8)) return 0
16+
res = res * 10 + pop
17+
}
18+
19+
return res
20+
};

algorithms/ReverseInteger/solution.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution(object):
2+
def reverse(self, x):
3+
"""
4+
:type x: int
5+
:rtype: int
6+
"""
7+
res = 0
8+
is_negative = x < 0
9+
x = abs(x)
10+
11+
while x > 0:
12+
res = res * 10 + x % 10
13+
x /= 10
14+
15+
res = res if not is_negative else - res
16+
return res if pow(-2, 31) <= res <= pow(2, 31) - 1 else 0

0 commit comments

Comments
 (0)