二進制手錶頂部有 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”。
在真實的面試中遇到過這道題?
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/binary-watch
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
class Solution {
public:
vector<string> readBinaryWatch(int num) {
vector<string> ret;
for(int i = 0; i < 12; i++)
for(int j = 0; j < 60; j++)
if(onecnt(i) + onecnt(j) == num)
ret.push_back(to_string(i) + ":" + (j < 10 ? "0" + to_string(j) : to_string(j)));
return ret;
}
int onecnt(int n)
{
int cnt = 0;
while(n)
{
n = n & (n - 1);
cnt++;
}
return cnt;
}
};