原題連接在這裏:https://leetcode.com/problems/binary-watch/html
題目:git
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).post
Each LED represents a zero or one, with the least significant bit on the right.url
For example, the above binary watch reads "3:25".spa
Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.code
Example:orm
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:htm
題解:blog
上面4個表示小時,下面6個表示分鐘,把小時向左移動6位 | 分鐘就是二進制表示。二進制表示中 1 bit的個數等於num時就把這個組合加到結果中。leetcode
能夠用Number of 1 Bits 或者Integer.bitCount()求出1 bit的個數.
Time Complexity: O(1), 12 * 60 * O(1). Space: O(1).
AC Java:
1 public class Solution { 2 public List<String> readBinaryWatch(int num) { 3 List<String> res = new ArrayList<String>(); 4 for(int h = 0; h<12; h++){ 5 for(int m = 0; m<60; m++){ 6 if(Integer.bitCount(h<<6 | m) == num){ 7 res.add(String.format("%d:%02d", h, m)); 8 } 9 } 10 } 11 return res; 12 } 13 }