Leetcode 401: Binary Watch

问题描述:
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). Each LED represents a zero or one, with the least significant bit on the right.
在这里插入图片描述
输出格式限定:
The hour must not contain a leading zero.
For example, “01:00” is not valid. It should be “1:00”.
The minute must be consist of two digits and may contain a leading zero.
For example, “10:2” is not valid. It should be “10:02”.

思路:
一个时间由两部分组成:时针+分针
我们如何判断一个时针,或者一个分针,需要亮几个灯?
如上图所示:为了表示分针51=32+16+2+1,需要亮四个灯;为了表示时针4,需要亮1个灯。我们可以把亮灯的数量转化为一个整数的二进制表达中1的数量。比如51的二进制表达为110011,它有4个1,所以对应亮4个灯

代码如下:

class Solution {
    public List<String> readBinaryWatch(int turnedOn) {
        List<String> list = new ArrayList<>();
        for(int h=0; h<=11; h++){
            for(int m=0; m<=59; m++){
                if(countOne(h)+countOne(m)==turnedOn){
                    String hour= Integer.toString(h);
                    String min= m<10? "0"+Integer.toString(m):Integer.toString(m);
                    list.add(hour+":"+min);
                }
            }
        }
        return list;
    }
    
    private int countOne(int n){
        //this function counts # of 1 in O(logn)
        int counter=0;
        while(n>0){
            if((n&1)==1){
                counter++;
            }
            n=n>>1;
        }
        return counter;
    }
}

时间复杂度: O(720logn)=O(logn)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值