[LeetCode] Convert Date to Binary

3280. Convert Date to Binary

You are given a string date representing a Gregorian calendar date in the yyyy-mm-dd format.

date can be written in its binary representation obtained by converting year, month, and day to their binary representations without any leading zeroes and writing them down in year-month-day format.

Return the binary representation of date.

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
func binary(x int) string {
if x == 0 {
return "0"
}
res := ""
for x > 0 {
res = strconv.Itoa(x%2) + res
x /= 2
}
return res
}

func convertDateToBinary(date string) string {
date += "-"
res := ""
val := 0

for _, ch := range date {
if ch >= '0' && ch <= '9' {
val = val*10 + int(ch-'0')
} else {
res += binary(val) + "-"
val = 0
}
}

return strings.TrimSuffix(res, "-")
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/09/08/PS/LeetCode/convert-date-to-binary/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.