File tree 1 file changed +62
-0
lines changed
src/main/java/com/leetcode/math
1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .leetcode .math ;
2
+
3
+ /**
4
+ * Level: Easy
5
+ * Problem Link: https://leetcode.com/problems/reverse-integer/
6
+ * Problem Description:
7
+ * Given a 32-bit signed integer, reverse digits of an integer.
8
+ * <p>
9
+ * Example 1:
10
+ * Input: 123
11
+ * Output: 321
12
+ * <p>
13
+ * Example 2:
14
+ * Input: -123
15
+ * Output: -321
16
+ * <p>
17
+ * Example 3:
18
+ * Input: 120
19
+ * Output: 21
20
+ * <p>
21
+ * Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed
22
+ * integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when
23
+ * the reversed integer overflows.
24
+ *
25
+ * @author rampatra
26
+ * @since 2019-05-31
27
+ */
28
+ public class ReverseInteger {
29
+
30
+ /**
31
+ * Reverses the input integer.
32
+ * Time complexity: O(d)
33
+ * where,
34
+ * d = number of digits in num
35
+ * <p>
36
+ * Runtime: <a href="https://leetcode.com/submissions/detail/232679205/">1 ms</a>.
37
+ *
38
+ * @param num an integer.
39
+ * @return the reverse of {@code num}.
40
+ */
41
+ private static int reverse (int num ) {
42
+ long reverse = 0 ;
43
+ int pop ;
44
+
45
+ while (num != 0 ) {
46
+ pop = num % 10 ;
47
+ num = num / 10 ;
48
+ reverse = reverse * 10 + pop ;
49
+ }
50
+
51
+ return reverse < Integer .MIN_VALUE || reverse > Integer .MAX_VALUE ? 0 : (int ) reverse ;
52
+ }
53
+
54
+ public static void main (String [] args ) {
55
+ System .out .println (reverse (0 ));
56
+ System .out .println (reverse (-0 ));
57
+ System .out .println (reverse (123 ));
58
+ System .out .println (reverse (-123 ));
59
+ System .out .println (reverse (Integer .MAX_VALUE ));
60
+ System .out .println (reverse (Integer .MIN_VALUE ));
61
+ }
62
+ }
You can’t perform that action at this time.
0 commit comments