LeetCode 401. 二进制手表
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 401. 二进制手表
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 題目
二進制手表頂部有 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
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. 解題
class Solution {vector<string> ans;int count; public:vector<string> readBinaryWatch(int num) {int i, j;for(i = 0; i < 12; ++i){for(j = 0; j < 60; ++j){if(count1(i)+count1(j) == num)ans.push_back(to_string(i)+":"+(j<10 ? ("0"+to_string(j)) : to_string(j)));}}return ans;}int count1(int n)//計算二進制1的個數{count = 0;while(n){n = n&(n-1);++count;}return count;} };總結
以上是生活随笔為你收集整理的LeetCode 401. 二进制手表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 剑指Offer - 面试题45. 把数组
- 下一篇: LeetCode 409. 最长回文串(