Skip to content

Commit 17ec19d

Browse files
committed
add 007
1 parent ee291e1 commit 17ec19d

File tree

3 files changed

+74
-1
lines changed

3 files changed

+74
-1
lines changed

Diff for: README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
| # | Title |
3333
| :--: | :------------------------------------------ |
3434
| 344 | [Reverse String][344] |
35-
35+
| 7 | [Reverse Integer][007] |
3636

3737
**其他**
3838

@@ -59,3 +59,4 @@
5959
[036]: https://github.com/andavid/leetcode-java/blob/master/note/036/README.md
6060
[048]: https://github.com/andavid/leetcode-java/blob/master/note/048/README.md
6161
[344]: https://github.com/andavid/leetcode-java/blob/master/note/344/README.md
62+
[007]: https://github.com/andavid/leetcode-java/blob/master/note/007/README.md

Diff for: note/007/README.md

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# [Reverse Integer][title]
2+
3+
## Description
4+
5+
Given a 32-bit signed integer, reverse digits of an integer.
6+
7+
**Example 1:**
8+
9+
```
10+
Input: 123
11+
Output: 321
12+
```
13+
14+
**Example 2:**
15+
16+
```
17+
Input: -123
18+
Output: -321
19+
```
20+
21+
**Example 3:**
22+
23+
```
24+
Input: 120
25+
Output: 21
26+
```
27+
28+
**Note:**
29+
30+
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
31+
32+
## 思路
33+
使用长整型保存结果。依次模 10 得到最右边一位。
34+
35+
## [完整代码][src]
36+
37+
```java
38+
class Solution {
39+
public int reverse(int x) {
40+
long result = 0;
41+
for (; x != 0; x /= 10) {
42+
result = result * 10 + x % 10;
43+
}
44+
if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
45+
return 0;
46+
}
47+
return (int)result;
48+
}
49+
}
50+
```
51+
52+
[title]: https://leetcode.com/problems/reverse-integer
53+
[src]: https://github.com/andavid/leetcode-java/blob/master/src/com/andavid/leetcode/_007/Solution.java

Diff for: src/com/andavid/leetcode/_007/Solution.java

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
public int reverse(int x) {
3+
long result = 0;
4+
for (; x != 0; x /= 10) {
5+
result = result * 10 + x % 10;
6+
}
7+
if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
8+
return 0;
9+
}
10+
return (int)result;
11+
}
12+
13+
public static void main(String[] args) {
14+
Solution solution = new Solution();
15+
System.out.println(solution.reverse(123));
16+
System.out.println(solution.reverse(-123));
17+
System.out.println(solution.reverse(120));
18+
}
19+
}

0 commit comments

Comments
 (0)