反转一个整数,例如:
>例子1: x = 123, return 321
>例子2: x = -123, return -321
输入的整数要求是一个 32bit 有符号数,如果反转后溢出,则输出 0
函数签名:
```go
func Reverse(x int32) int32 {
}
```
给出你的答案吧!
第 1 条附言 ·
12 楼的答案不错。
```go
func reverse(x int) ( num int) {
for x != 0 {
num = num*10 + x%10
x = x / 10
}
// 使用 math 包中定义好的最大最小值
if num > math.MaxInt32 || num < math.MinInt32 {
return 0
}
return
}
```
感觉有些熟悉,原来以前刷过这道题,又手敲一遍
```go
func reverse(x int) ( num int) {
for x != 0 {
num = num*10 + x%10
x = x / 10
}
MaxInt32 := 1<<31 - 1
MinInt32 := -1 << 31
if num > MaxInt32 || num < MinInt32 {
return 0
}
return
}
```
from: [https://leetcode.com/problems/reverse-integer/description/](https://leetcode.com/problems/reverse-integer/description/)
#12
更多评论
```go
func Reverse(x int32) int32 {
var xx, rx, tnum, pos, negative int32
//备份原值
xx = x
var posNum, posStart, maxLan int
//int32最大长度
maxLan = 11
//判断是否负数
negative = 1
if x < 0 {
negative = -1
xx = xx * -1
}
for i := maxLan; i >= 0; i-- {
tnum = int32(math.Pow10(i))
if xx >= tnum {
pos = xx / tnum
if pos > 0 || posStart > 0 {
if posStart == 0 {
posStart = 1
}
fmt.Println(i, pos)
posNum++
rx += pos * (int32(math.Pow10(posNum - 1)))
}
xx = xx - pos*tnum
}
}
rx = rx * negative
return rx
}
```
#1