Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions leetcode/3201-3300/3280.Convert-Date-to-Binary/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# [3280.Convert Date to Binary][title]

## Description
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`.

**Example 1:**

```
Input: date = "2080-02-29"

Output: "100000100000-10-11101"

Explanation:

100000100000, 10, and 11101 are the binary representations of 2080, 02, and 29 respectively.
```

**Example 2:**

```
Input: date = "1900-01-01"

Output: "11101101100-1-1"

Explanation:

11101101100, 1, and 1 are the binary representations of 1900, 1, and 1 respectively.
```

## 结语

如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-golang-algorithm][me]

[title]: https://leetcode.com/problems/convert-date-to-binary
[me]: https://github.com/kylesliu/awesome-golang-algorithm
30 changes: 30 additions & 0 deletions leetcode/3201-3300/3280.Convert-Date-to-Binary/Solution.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package Solution

import "bytes"

func convert(s string) string {
base := 0
for _, b := range s {
base = base*10 + int(b-'0')
}
buf := bytes.NewBuffer([]byte{})
for base > 0 {
mod := base & 1
if mod == 1 {
buf.WriteByte('1')
} else {
buf.WriteByte('0')
}
base >>= 1
}
bs := buf.Bytes()
for s, e := 0, len(bs)-1; s < e; s, e = s+1, e-1 {
bs[s], bs[e] = bs[e], bs[s]
}
return string(bs)
}

func Solution(date string) string {
// 0:4, 5:7 8:end
return convert(date[:4]) + "-" + convert(date[5:7]) + "-" + convert(date[8:])
}
38 changes: 38 additions & 0 deletions leetcode/3201-3300/3280.Convert-Date-to-Binary/Solution_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package Solution

import (
"reflect"
"strconv"
"testing"
)

func TestSolution(t *testing.T) {
// 测试用例
cases := []struct {
name string
inputs string
expect string
}{
{"TestCase1", "2080-02-29", "100000100000-10-11101"},
{"TestCase2", "1900-01-01", "11101101100-1-1"},
}

// 开始测试
for i, c := range cases {
t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) {
got := Solution(c.inputs)
if !reflect.DeepEqual(got, c.expect) {
t.Fatalf("expected: %v, but got: %v, with inputs: %v",
c.expect, got, c.inputs)
}
})
}
}

// 压力测试
func BenchmarkSolution(b *testing.B) {
}

// 使用案列
func ExampleSolution() {
}
Loading