Golang刷题找工作 Leetcode-7

题目 Reverse Integer.go

Given a 32-bit signed integer, reverse digits of an integer.

输入一个32位整数,输出反转后的结果

例如,输入123,输出321

思路

循环取余数

需要注意越界

code

func reverse(x int) int {
res := 0
for x != 0 {
carry := x % 10
res = res*10 + carry
if res > math.MaxInt32 || res < math.MinInt32 {
return 0
}
x /= 10
}
return res
}