401. Binary Watch

本文介绍了一种算法,用于解决二进制手表显示特定数量LED点亮时的所有可能时间。通过两种方法实现:一是生成满足条件的二进制数再转换成时间;二是直接枚举所有合法时间并计数LED点亮的数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 above binary watch reads “3:25”.

Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.

Example:

Input: n = 1
Return: [“1:00”, “2:00”, “4:00”, “8:00”, “0:01”, “0:02”, “0:04”, “0:08”, “0:16”, “0:32”]

Note:
+ The order of output does not matter.
+ 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”.

题解

4位二进制从高到低表示0~11,6位二进制表示0~59,求有num为1的可能时间(无需按序)

首先想到的是先找出10位二进制中1个数为num的数,于是写了一个generateBinary函数,将所有合法的数放入一个集合中,之后遍历集合,按要求输出时间,小时无头0,分钟要补头0。
(若使用set即可按序)

class Solution {
public:
    vector<string> readBinaryWatch(int num) {
        vector<string> a;
        if(num < 0 || num >= 10)    return a;
        unordered_set<int> haha;
        generateBinary(haha, 0, 0, 0, num);
        for(unordered_set<int>::iterator itr = haha.begin(); itr != haha.end(); itr++){
            int hour = *itr >> 6, minute = *itr & 63;
            if(hour >= 12 || minute >= 60)  continue;
            a.push_back(to_string(hour) + ":" + (minute < 10 ? "0" : "") + to_string(minute));
        }
        return a;
    }
private:
    //i表示当前位,j表示1的个数,t表示生成的数,满足条件j=num就将其放入集合haha中
    void generateBinary(unordered_set<int>& haha, int t, int i, int j, int num){
        if(i > 10)  return;
        if(j == num){
            haha.insert(t);
            return;
        }
        generateBinary(haha, t | 1 << i, i + 1, j + 1, num);
        generateBinary(haha, t, i + 1, j, num);
    }
};

上一种方法比较麻烦,有没有简单的方法呢?
我们注意到上一种方法是先找出满足条件num个1的数,但生成的数有些是不符合时间规范的,比如hour>=12,minute>=60,造成了浪费。
既然符合规范的数是有限的,可以直接枚举所有符合规范的时间0:00~11:59,判断是否符合要求num个1,于是写一个简单的找出1的个数的函数count_1。相比上一个方法效率要高出很多,同时也保证了有序。

class Solution {
public:
    vector<string> readBinaryWatch(int num) {
        vector<string> a;
        for(int i = 0; i < 12; i++){
            for(int j = 0; j < 60; j++){
                if(count_1(i << 6 | j) == num){
                    a.push_back(to_string(i) + ":" + (j < 10 ? "0" : "") + to_string(j));
                }
            }
        }
        return a;
    }
private:
    int count_1(int num){
        if(num == 0)    return 0;
        return (num & 1) + count_1(num >> 1);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值