加载中...
401-二进制手表(Binary Watch)
发表于:2021-12-03 | 分类: 简单
字数统计: 431 | 阅读时长: 2分钟 | 阅读量:

原文链接: https://leetcode-cn.com/problems/binary-watch

英文原文

A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right.

  • For example, the below binary watch reads "4:51".

Given an integer turnedOn which represents the number of LEDs that are currently on, return all possible times the watch could represent. You may return the answer in any order.

The hour must not contain a leading zero.

  • For example, "01:00" is not valid. It should be "1:00".

The minute must be consist of two digits and may contain a leading zero.

  • For example, "10:2" is not valid. It should be "10:02".

 

Example 1:

Input: turnedOn = 1
Output: ["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"]

Example 2:

Input: turnedOn = 9
Output: []

 

Constraints:

  • 0 <= turnedOn <= 10

中文题目

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

  • 例如,下面的二进制手表读取 "3:25"

(图源:WikiMedia - Binary clock samui moon.jpg ,许可协议:Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0)

给你一个整数 turnedOn ,表示当前亮着的 LED 的数量,返回二进制手表可以表示的所有可能时间。你可以 按任意顺序 返回答案。

小时不会以零开头:

  • 例如,"01:00" 是无效的时间,正确的写法应该是 "1:00"

分钟必须由两位数组成,可能会以零开头:

  • 例如,"10:2" 是无效的时间,正确的写法应该是 "10:02"

 

示例 1:

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

示例 2:

输入:turnedOn = 9
输出:[]

 

提示:

  • 0 <= turnedOn <= 10

通过代码

高赞题解

QQ截图20190629200856.png


class Solution {

public:

    vector<string> readBinaryWatch(int num) {

        vector<string> res;

        //直接遍历  0:00 -> 12:00   每个时间有多少1

        for (int i = 0; i < 12; i++) {

            for (int j = 0; j < 60; j++) {

                if (count1(i) + count1(j) == num) {

                    res.push_back(to_string(i)+":"+

                                  (j < 10 ? "0"+to_string(j) : to_string(j)));

                }

            }

        }

        return res;

    }

    //计算二进制中1的个数

    int count1(int n) {

        int res = 0;

        while (n != 0) {

            n = n & (n - 1);

            res++;

        }

        return res;

    }

};

统计信息

通过次数 提交次数 AC比率
55626 90363 61.6%

提交历史

提交时间 提交结果 执行时间 内存消耗 语言

相似题目

题目 难度
电话号码的字母组合 中等
位1的个数 简单
上一篇:
390-消除游戏(Elimination Game)
下一篇:
412-Fizz Buzz
本文目录
本文目录