File tree 5 files changed +58
-0
lines changed
algorithms/ReverseInteger
5 files changed +58
-0
lines changed Original file line number Diff line number Diff line change @@ -184,6 +184,7 @@ All solutions will be accepted!
184
184
| 581| [ Shortest Unsorted Continuous Subarray] ( https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray/description/ ) | [ java/py/js] ( ./algorithms/ShortestUnsortedContinuousSubarray ) | Easy|
185
185
| 443| [ String Compression] ( https://leetcode-cn.com/problems/string-compression/description/ ) | [ java/py/js] ( ./algorithms/StringCompression ) | Easy|
186
186
| 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|
187
188
188
189
# Database
189
190
| #| Title| Solution| Difficulty|
Original file line number Diff line number Diff line change
1
+ # Reverse Integer
2
+ This problem is easy to solve
Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ } ;
Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments