Golang 基础
鸣谢: LeetCode-In-Go
7. Reverse Integer
题目
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
解题思路
详见 程序注释
解题代码
解决方案
package problem0007
import (
"math"
)
func reverse(x int) int {
sign := 1
// 处理负数
if x < 0 {
sign = -1
x = -1 * x
}
res := 0
for x > 0 {
// 取出x的末尾
temp := x % 10
// 放入 res 的开头
res = res*10 + temp
// x 去除末尾
x = x / 10
}
// 还原 x 的符号到 res
res = sign * res
// 处理 res 的溢出问题
if res > math.MaxInt32 || res < math.MinInt32 {
res = 0
}
return res
}
测试代码
package problem0007
import (
"testing"
"github.com/stretchr/testify/assert"
)
type para struct {
one int
}
type ans struct {
one int
}
type question struct {
p para
a ans
}
func Test_OK(t *testing.T) {
ast := assert.New(t)
qs := []question{
question{
p: para{
one: 123,
},
a: ans{
one: 321,
},
},
question{
p: para{
one: -123,
},
a: ans{
one: -321,
},
},
question{
p: para{
one: 1234567899,
},
a: ans{
one: 0,
},
},
question{
p: para{
one: -1234567899,
},
a: ans{
one: 0,
},
},
}
for _, q := range qs {
a, p := q.a, q.p
ast.Equal(a.one, reverse(p.one), "输入:%v", p)
}
}
个人解题尝试过程
第一次
func reverse(x int) int {
// 先去掉超出范围的
if x < -2147483648 || x > 2147483647 || x == 0 {
return 0
}
result := make([]int, 32) // 定义一个32位来存放每一位的数据
i := 0
var f bool
if x >= 0 {
f = true
} else {
f = false
}
for ; x != 0; i++ {
result[i] = x % 10
x = x / 10
}
var s int
up := 1
for ; i >= 0; i-- {
if result[i] == 0 {
continue
}
s = s + result[i] * up
up = up * 10
}
if f == true {
return s
} else {
s = -s
// fmt.Println(s)
return -s
}
}
结果:
这里的问题是: 没有考虑到对应的中间的0被我去掉了,我只想去掉最后面的0。
第二次
func reverse(x int) int {
// 先去掉超出范围的
if x < -2147483648 || x > 2147483647 || x == 0 {
return 0
}
result := make([]int, 32) // 定义一个32位来存放每一位的数据
i := 0
var f bool
if x >= 0 {
f = true
} else {
f = false
}
for ; x != 0; i++ {
result[i] = x % 10
x = x / 10
}
var s int
up := 1
i = i - 1
for ; i >= 0; i-- {
// if result[i] == 0 {
// continue
// }
s = s + result[i] * up
up = up * 10
}
if f == true {
return s
} else {
s = -s
// fmt.Println(s)
return -s
}
}
这里存在的问题是:
超出范围的数字没有返回0,是最开始的判断有误?
经过修改之后就是下面的状态:
最终通过
func reverse(x int) int {
// 先去掉超出范围的
// var t int64
// t = int64(x)
// fmt.Println(t - 2147483647)
if x < math.MinInt32 || x > math.MaxInt32 || x == 0 {
return 0
}
// if x + -2147483648 > 0 || x - 2147483647 < 0 || x == 0 {
// return 0
// }
result := make([]int, 32) // 定义一个32位来存放每一位的数据
i := 0
var f bool
if x >= 0 {
f = true
} else {
f = false
}
for ; x != 0; i++ {
result[i] = x % 10
x = x / 10
}
var s int
up := 1
i = i - 1
for ; i >= 0; i-- {
// if result[i] == 0 {
// continue
// }
s = s + result[i] * up
up = up * 10
}
if s > math.MaxInt32 || s < math.MinInt32 {
s = 0
}
if f == true {
return s
} else {
s = -s
// fmt.Println(s)
return -s
}
}
个人测试代码
func main() {
// 处理一下过程中遇到问题的用例,一步步调试
fmt.Println(reverse(123))
fmt.Println(reverse(120))
fmt.Println(reverse(-120))
fmt.Println(reverse(-321))
fmt.Println(reverse(901000))
fmt.Println(reverse(1534236469))
}