12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- package main
- import (
- "math"
- )
- func reverseOld(x int) int {
- stack := make([]int, 0)
- neg := false
- if x < 0 {
- neg = true
- x = -x
- }
- for remain := x % 10; x > 0; remain = x % 10 {
- stack = append(stack, remain)
- x /= 10
- }
- res := 0
- for i, v := range stack {
- res += v * int(math.Pow10(len(stack)-i-1))
- }
- if res > 1<<31-1 || res < -1<<31 {
- return 0
- }
- if neg {
- return -res
- }
- return res
- }
- func reverse(x int) int {
- res := int64(0)
- for ; x != 0; x /= 10 {
- res = res*10 + int64(x%10)
- // overflow: -2^31 ~ 2^31-1
- // if res > 1 << 31 - 1 || res < -1 << 31 { return 0 }
- if res < math.MinInt32 || res > math.MaxInt32 {
- return 0
- }
- }
- return int(res)
- }
- // func main() {
- // fmt.Println(reverse(1234))
- // }
|