Skip to content

Commit dd99c2c

Browse files
authored
Merge pull request #120 from NovaHe/feature/401
feature/401: add a simpler solution
2 parents 678bc75 + bff8947 commit dd99c2c

File tree

1 file changed

+38
-3
lines changed

1 file changed

+38
-3
lines changed

leetcode/0401.Binary-Watch/401. Binary Watch.go

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,11 @@ var (
2424
}
2525
)
2626

27-
func readBinaryWatch(num int) []string {
27+
func readBinaryWatch1(num int) []string {
28+
var res []string
2829
if num > 8 {
29-
return []string{}
30+
return res
3031
}
31-
res := []string{}
3232
for i := 0; i <= num; i++ {
3333
for j := 0; j < len(hourMap[i]); j++ {
3434
for k := 0; k < len(minuteMap[num-i]); k++ {
@@ -88,3 +88,38 @@ func findReadBinaryWatchHour(target, index int, c []int, res *[]string) {
8888
c = c[:len(c)-1]
8989
}
9090
}
91+
92+
func readBinaryWatch(num int) []string {
93+
memo := make([]int, 60)
94+
// count the number of 1 in a binary number
95+
count := func(n int) int {
96+
if memo[n] != 0 {
97+
return memo[n]
98+
}
99+
originN, res := n, 0
100+
for n != 0 {
101+
n = n & (n - 1)
102+
res++
103+
}
104+
memo[originN] = res
105+
return res
106+
}
107+
// fmtMinute format minute 0:1 -> 0:01
108+
fmtMinute := func(m int) string {
109+
if m < 10 {
110+
return "0" + strconv.Itoa(m)
111+
}
112+
return strconv.Itoa(m)
113+
}
114+
115+
var res []string
116+
// traverse 0:00 -> 12:00
117+
for i := 0; i < 12; i++ {
118+
for j := 0; j < 60; j++ {
119+
if count(i)+count(j) == num {
120+
res = append(res, strconv.Itoa(i)+":"+fmtMinute(j))
121+
}
122+
}
123+
}
124+
return res
125+
}

0 commit comments

Comments
 (0)