算法链接

https://leetcode-cn.com/problems/reverse-integer/solution/zheng-shu-fan-zhuan-by-leetcode/

解法

  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. "strconv"
  6. )
  7. func main() {
  8. x := 1534236469
  9. x = reverse(x)
  10. fmt.Println(x)
  11. }
  12. // 用字符串的解法
  13. func reverse(x int) int {
  14. f := false
  15. if x < 0 {
  16. x *= -1
  17. f = true
  18. }
  19. str := strconv.Itoa(x)
  20. var newStr string
  21. l := len(str)
  22. for i := l - 1; i >= 0; i-- {
  23. newStr += string(str[i])
  24. }
  25. x, _ = strconv.Atoi(newStr)
  26. if f {
  27. x *= -1
  28. }
  29. if x > math.MaxInt32 || x < math.MinInt32 {
  30. x = 0
  31. }
  32. return x
  33. }
  34. // 用取余加除法的方式做
  35. func reverse1(x int) int {
  36. n := 0
  37. for x != 0 {
  38. n = n * 10 + x % 10
  39. x = x / 10
  40. }
  41. if n > math.MaxInt32 || n < math.MinInt32 {
  42. n = 0
  43. }
  44. return n
  45. }