算法链接
https://leetcode-cn.com/problems/reverse-integer/solution/zheng-shu-fan-zhuan-by-leetcode/
解法
package main
import (
"fmt"
"math"
"strconv"
)
func main() {
x := 1534236469
x = reverse(x)
fmt.Println(x)
}
// 用字符串的解法
func reverse(x int) int {
f := false
if x < 0 {
x *= -1
f = true
}
str := strconv.Itoa(x)
var newStr string
l := len(str)
for i := l - 1; i >= 0; i-- {
newStr += string(str[i])
}
x, _ = strconv.Atoi(newStr)
if f {
x *= -1
}
if x > math.MaxInt32 || x < math.MinInt32 {
x = 0
}
return x
}
// 用取余加除法的方式做
func reverse1(x int) int {
n := 0
for x != 0 {
n = n * 10 + x % 10
x = x / 10
}
if n > math.MaxInt32 || n < math.MinInt32 {
n = 0
}
return n
}