LeetCode - 401. Binary Watch

链接

401. Binary Watch

题意

有一块二进制表,其中有4个LED灯代表时(0-11),6个LED灯代表分(0-59)。现给定一个非负整数n,代表有n个灯亮,列出所有可能的时间(顺序可任意)。

思路

来自讨论区,枚举每一种可能,注意h是乘以64(作为第7个灯,第6个是32),利用bitCount方法即计算出亮的灯。

代码

Java:

public class Solution {
   public List<String> readBinaryWatch(int num) {
       List<String> times = new ArrayList<>();
       for (int h=0; h<12; h++)
       for (int m=0; m<60; m++)
           if (Integer.bitCount(h * 64 + m) == num)
               times.add(String.format("%d:%02d", h, m));
   return times;        
}
}
posted @ 2017-05-16 13:40  zyoung  阅读(118)  评论(0编辑  收藏  举报