-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_int.go
More file actions
88 lines (64 loc) · 1.79 KB
/
reverse_int.go
File metadata and controls
88 lines (64 loc) · 1.79 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package reverseInt
import (
"fmt"
"strconv"
"math"
)
//Original problem: https://leetcode.com/problems/reverse-integer/
func main() {
testIntP := 4345
testIntN := -123
fmt.Println("and the answer is: ", reverse(testIntP))
fmt.Println("and the answer is: ", reverse(testIntN))
fmt.Println("try reverseTwo method")
fmt.Println( reverseTwo(testIntP))
fmt.Println( reverseTwo(testIntN))
}
//original solution couldn't handle negatives
//referenced this for help: https://leetcode.com/problems/reverse-integer/discuss/184798/golang
func reverse(x int) int {
orgS := ""
newS := ""
//convert int to string using "i to a" method built into Go
if x > 0{
orgS = strconv.Itoa(x)
} else {
//in case X is negative
orgS = strconv.Itoa(-x)
}
fmt.Println(orgS)
for i := len(orgS)-1; i> -1; i--{
newS += string(orgS[i])
}
fmt.Println("new string", newS)
//convert string into a 32 bit int using "a to i" method built into Go which requires both an int and err as output
//err can be ignored by using "_" or you can use if statement to include check for err
newInt, err := strconv.Atoi(newS)
if err == nil {
fmt.Println(newInt)
}
//add negative back in at the end if part of original value
if x < 0{
newInt = -newInt
fmt.Println(newInt)
}
//wasn't passing leetcode tests, because wasn't accounting for integer overflow. this is the fix
//check for integer overflows (https://stackoverflow.com/questions/33641717/detect-signed-int-overflow-in-go)
if newInt > math.MaxInt32 || newInt < math.MinInt32 {
return 0
}
return newInt
}
//alt solution: USE MODULUS! (after reading discussion on leetcode)
func reverseTwo (x int) int {
sum :=0
for x !=0 {
sum = sum*10 +x%10
x = x/10
}
//also needed to pass
if sum > math.MaxInt32 || sum < math.MinInt32 {
return 0
}
return sum
}