-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution3280.go
60 lines (52 loc) · 1.13 KB
/
solution3280.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
59
60
package solution3280
import (
"fmt"
"slices"
"strconv"
)
// ============================================================================
// 3280. Convert Date to Binary
// URL: https://leetcode.com/problems/convert-date-to-binary/
// ============================================================================
func convertDateToBinaryV2(date string) string {
var (
buf = make([]rune, 0, 24)
p = []int{1000, 100, 10, 1, 0, 10, 1, 0, 10, 1, 0}
)
numToBin := func(num int, dash bool) {
b := make([]rune, 0, 4)
for num > 0 {
b = append(b, rune(num%2+'0'))
num = num / 2
}
slices.Reverse(b)
buf = append(buf, b...)
if dash {
buf = append(buf, '-')
}
}
var v int
num := 0
idx := 0
for i := 0; i < len(date); i++ {
if date[i] == '-' {
numToBin(num, true)
num = 0
idx++
continue
}
v = int(date[i]-'0') * p[idx]
num += v
idx++
if i == len(date)-1 {
numToBin(num, false)
}
}
return string(buf)
}
func convertDateToBinaryV1(date string) string {
a, _ := strconv.Atoi(date[:4])
b, _ := strconv.Atoi(date[5:7])
c, _ := strconv.Atoi(date[8:])
return fmt.Sprintf("%b-%b-%b", a, b, c)
}