401. Binary Watch

A binary watch has 4 LEDs onthe top which represent the hours (0-11), and the 6 LEDs on the bottomrepresent the minutes (0-59).

Each LED represents a zero orone, with the least significant bit on the right.

For example, the above binary watchreads "3:25".

Given a non-negative integer nwhich represents the number of LEDs that are currently on, return all possibletimes the watch could represent.

Example:

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:

The order of output does notmatter.

The hour must not contain aleading zero, for example "01:00" is not valid, it should be"1:00".

The minute must be consist oftwo digits and may contain a leading zero, for example "10:2" is notvalid, it should be "10:02".

    翻译:二进制表在顶部有4LED,表示小时(0-11),底部的6LED表示分钟(0-59)。每个LED表示零或一,右边的最低有效位。

    例如,上面的二进制表读数“3:25”。给定一个非负整数n代表当前打开的LED的数量,返回手表可能表示的所有可能的时间。

    例:输入:n = 1

   返 回:[1:00”,“2:00”,“4:00”,“8:00”,“0:01”,“0:02”,“0:04”,“,“0:16”,“0:32]

    注意:

    输出的顺序无关紧要。

    小时不能包含前导零,例如“01:00”无效,应为“1:00”。

    分钟必须由两位数字组成,并且可能包含前导零,例如“102”无效,应10:02”。

    题目有两个注意点,一个是二进制表,这个可以利用计算二进制的方法来思考。第二就是需要注意格式的变换。这题完全不会,参考的别人的,写的真的太好了,利用二进制的表示方法来计算时间。具体代码如下:

public class Solution {

    public List<String>readBinaryWatch(int num) {

        List<String> times = newArrayList<>();

          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;

    }

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值