funcreverse(x int)int { var ( n int k int f int ) f = 1 if x < 0 { f = -1 x *= f } for x > 0 { if k != 0 { n *= 10 } n += x % 10 x /= 10 k++ } n *= f if n > 2147483648 || n < -2147483648 { n = 0 } return n }
本地测试
package main
import ( "fmt" )
funcmain() { n := 123 fmt.Println(reverse(n), n) n = -123 fmt.Println(reverse(n), n) n = 120 fmt.Println(reverse(n), n) n = 1534236469 fmt.Println(reverse(n), n) n = 1563847412 fmt.Println(reverse(n), n) }