首页 > 其他 > 详细

leetcode 401. 二进制手表(Binary Watch)

时间:2019-03-22 13:56:26      阅读:149      评论:0      收藏:0      [点我收藏+]

题目描述:

二进制手表顶部有 4 个 LED 代表小时(0-11),底部的 6 个 LED 代表分钟(0-59)

每个 LED 代表一个 0 或 1,最低位在右侧。
技术分享图片

例如,上面的二进制手表读取 “3:25”。

给定一个非负整数 n 代表当前 LED 亮着的数量,返回所有可能的时间。

示例:

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

注意事项:

  • 输出的顺序没有要求。
  • 小时不会以零开头,比如 “01:00” 是不允许的,应为 “1:00”。
  • 分钟必须由两位数组成,可能会以零开头,比如 “10:2” 是无效的,应为 “10:02”。

解法:

class Solution {
public:
    string toString(int num){
        string res = "";
        if(num == 0){
            return "0";
        }
        while(num != 0){
            res = char('0' + num%10) + res;
            num /= 10;
        }
        return res;
    }
    
    int getOnes(int num){
        int res = 0;
        while(num != 0){
            if(num&1){
                res++;
            }
            num >>= 1;
        }
        return res;
    }
    
    vector<string> readBinaryWatch(int num) {
        if(num > 10){
            num = 10;
        }
        vector<vector<string>> hours(11, vector<string>());
        vector<vector<string>> mins(11, vector<string>());
        for(int i = 0; i < 12; i++){
            int idx = getOnes(i);
            string s = toString(i);
            hours[idx].push_back(s);
        }
        
        for(int i = 0; i < 60; i++){
            int idx = getOnes(i);
            string s = toString(i);
            if(s.size() == 1){
                s = '0' + s;
            }
            mins[idx].push_back(s);
        }
        
        vector<string> res;
        for(int i = 0; i <= num; i++){
            for(string h : hours[i]){
                for(string m : mins[num - i]){
                    res.push_back(h + ':' + m);
                }
            }
        }
        return res;
    }
};

leetcode 401. 二进制手表(Binary Watch)

原文:https://www.cnblogs.com/zhanzq/p/10577732.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!