leetcode401二进制手表

leetcode 401 Binary Watch

Posted by BY on November 1, 2020

前言

持续更新了

正文

问题来源

本问题来自leetcode上的401题。

问题描述

二进制手表顶部有 4 个 LED 代表 小时(0-11),底部的 6 个 LED 代表 分钟(0-59)。
每个 LED 代表一个 0 或 1,最低位在右侧。

示例 1:

输入: n = 1
返回: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]

分析:

func readBinaryWatch(num int) []string {
    res := make([]string, 0)
    for i := 0; i < 12; i++ {
        for j := 0; j < 60; j++ {
            if countBit(i) + countBit(j) == num {
                if j < 10 {
                    tmp := strconv.Itoa(i)+":0"+strconv.Itoa(j)
                    res = append(res, tmp)
                } else {
                    tmp := strconv.Itoa(i)+":"+strconv.Itoa(j)
                    res = append(res, tmp)
                }
            }
        }
    }
    return res
}

func countBit(num int) int {
    count := 0
    for num != 0 {
        count++
        num = num&(num-1)
    }
    return count
}

总结:

勤思考。

结语

不管怎么样好好加油。