7.go 733 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. func reverseOld(x int) int {
  7. stack := make([]int, 0)
  8. neg := false
  9. if x < 0 {
  10. neg = true
  11. x = -x
  12. }
  13. for remain := x % 10; x > 0; remain = x % 10 {
  14. stack = append(stack, remain)
  15. x /= 10
  16. }
  17. res := 0
  18. for i, v := range stack {
  19. res += v * int(math.Pow10(len(stack)-i-1))
  20. }
  21. if res > 1<<31-1 || res < -1<<31 {
  22. return 0
  23. }
  24. if neg {
  25. return -res
  26. }
  27. return res
  28. }
  29. func reverse(x int) int {
  30. res := int64(0)
  31. for ; x != 0; x /= 10 {
  32. res = res*10 + int64(x%10)
  33. // overflow: -2^31 ~ 2^31-1
  34. // if res > 1 << 31 - 1 || res < -1 << 31 { return 0 }
  35. if res < math.MinInt32 || res > math.MaxInt32 {
  36. return 0
  37. }
  38. }
  39. return int(res)
  40. }
  41. func main() {
  42. fmt.Println(reverse(1234))
  43. }