mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-06 17:44:10 +08:00
Merge pull request #120 from NovaHe/feature/401
feature/401: add a simpler solution
This commit is contained in:
@ -24,11 +24,11 @@ var (
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
func readBinaryWatch(num int) []string {
|
func readBinaryWatch1(num int) []string {
|
||||||
|
var res []string
|
||||||
if num > 8 {
|
if num > 8 {
|
||||||
return []string{}
|
return res
|
||||||
}
|
}
|
||||||
res := []string{}
|
|
||||||
for i := 0; i <= num; i++ {
|
for i := 0; i <= num; i++ {
|
||||||
for j := 0; j < len(hourMap[i]); j++ {
|
for j := 0; j < len(hourMap[i]); j++ {
|
||||||
for k := 0; k < len(minuteMap[num-i]); k++ {
|
for k := 0; k < len(minuteMap[num-i]); k++ {
|
||||||
@ -88,3 +88,38 @@ func findReadBinaryWatchHour(target, index int, c []int, res *[]string) {
|
|||||||
c = c[:len(c)-1]
|
c = c[:len(c)-1]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func readBinaryWatch(num int) []string {
|
||||||
|
memo := make([]int, 60)
|
||||||
|
// count the number of 1 in a binary number
|
||||||
|
count := func(n int) int {
|
||||||
|
if memo[n] != 0 {
|
||||||
|
return memo[n]
|
||||||
|
}
|
||||||
|
originN, res := n, 0
|
||||||
|
for n != 0 {
|
||||||
|
n = n & (n - 1)
|
||||||
|
res++
|
||||||
|
}
|
||||||
|
memo[originN] = res
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
// fmtMinute format minute 0:1 -> 0:01
|
||||||
|
fmtMinute := func(m int) string {
|
||||||
|
if m < 10 {
|
||||||
|
return "0" + strconv.Itoa(m)
|
||||||
|
}
|
||||||
|
return strconv.Itoa(m)
|
||||||
|
}
|
||||||
|
|
||||||
|
var res []string
|
||||||
|
// traverse 0:00 -> 12:00
|
||||||
|
for i := 0; i < 12; i++ {
|
||||||
|
for j := 0; j < 60; j++ {
|
||||||
|
if count(i)+count(j) == num {
|
||||||
|
res = append(res, strconv.Itoa(i)+":"+fmtMinute(j))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
Reference in New Issue
Block a user