1. 程式人生 > >leetcode 401. 二進制手表(Binary Watch)

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

輸出 toc 註意事項 wid eight push_back 位數 題目 目錄

目錄

  • 題目描述:
  • 示例:
  • 解法:

題目描述:

二進制手表頂部有 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)