401. Binary Watch

来源:互联网 发布:网络神豪系统txt下载 编辑:程序博客网 时间:2024/06/14 14:54

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);    }};
0 0
原创粉丝点击