-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
58 lines (50 loc) · 932 Bytes
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package main
import (
"fmt"
"math"
"strconv"
)
/*
@Create by GoLand
@Author: hong
@Time: 2018/7/27 16:39
@File: main.go
*/
/*
Question Description:
Given a 32-bit signed integer, reverse digits of an integer.
*/
func main() {
fmt.Println(Reverse(1534236469))
}
func Reverse(x int) int {
xString := strconv.Itoa(x)
var byteData []byte
for i := len(xString) - 1; i >= 0; i-- {
byteData = append(byteData, byte(xString[i]))
}
if string(byteData[len(byteData)-1]) == "-" {
byteData = byteData[:len(byteData)-1]
byteData = append([]byte("-"), byteData...)
}
n, err := strconv.Atoi(string(byteData))
if err != nil {
panic(err)
}
if n > math.MaxInt32 || n < math.MinInt32 {
return 0
}
return n
}
//leetcode go solution
func reverse(x int) int {
var resp int
for x != 0 {
resp = resp*10 + x%10
x /= 10
if resp > math.MaxInt32 || resp < math.MinInt32 {
return 0
}
}
return resp
}