-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse-integer.go
More file actions
51 lines (42 loc) · 836 Bytes
/
reverse-integer.go
File metadata and controls
51 lines (42 loc) · 836 Bytes
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
package main
import (
"fmt"
"math"
)
// source: https://leetcode.com/problems/reverse-integer/
func reverse(x int) (res int) {
var zeros int
for d := 0; x != 0; x = x / 10 {
d = x % 10
if d == 0 {
if res != 0 {
zeros++
}
continue
}
res *= int(math.Pow10(1 + zeros))
res += d
zeros = 0
}
if res > math.MaxInt32 || res < math.MinInt32 {
return 0
}
return
}
func main() {
// Example 4
var x5 = 24077
fmt.Println("Expected: 77042 Output: ", reverse(x5))
// Example 3
var x3 int = 120
fmt.Println("Expected: 21 Output: ", reverse(x3))
// Example 1
var x1 int = 123
fmt.Println("Expected: 321 Output: ", reverse(x1))
// Example 2
var x2 int = -123
fmt.Println("Expected: -321 Output: ", reverse(x2))
// Example 4
var x4 int = -12
fmt.Println("Expected: -21 Output: ", reverse(x4))
}