Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 270ed1b

Browse files
committed
ReverseInteger done
1 parent cde6e83 commit 270ed1b

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
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+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /