7.go 735 B

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