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 a390684

Browse files
committed
fix leetcode 0007 with go
1 parent da427cd commit a390684

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# 7. 整数反转
2+
3+
## 链接
4+
https://leetcode-cn.com/problems/reverse-integer/
5+
6+
## 难度
7+
简单
8+
9+
## 描述
10+
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
11+
12+
示例 1:
13+
```text
14+
输入: 123
15+
输出: 321
16+
```
17+
示例 2:
18+
```text
19+
输入: -123
20+
输出: -321
21+
```
22+
示例 3:
23+
```text
24+
输入: 120
25+
输出: 21
26+
```
27+
注意:
28+
29+
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−2<sup>31</sup>, 2<sup>31</sup> − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
30+
31+
## 思路
32+
33+
对 x 循环
34+
取出最后一个数,就是 x % 10
35+
x 去掉最后一个数,就是 x / 10
36+
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package _007_Reverse_Integer
2+
3+
import "math"
4+
5+
func reverse(x int) int {
6+
symbol := 1
7+
if x < 0 {
8+
symbol = -1
9+
x = 0 - x
10+
}
11+
12+
r := 0
13+
for x > 0 {
14+
tmp := x % 10
15+
r = r*10 + tmp
16+
x = x / 10
17+
}
18+
19+
r = symbol * r
20+
21+
if r > math.MaxInt32 || r < math.MinInt32 {
22+
r = 0
23+
}
24+
return r
25+
}

0 commit comments

Comments
(0)

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