# LeetCode 401. Binary Watch

## Description

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.

For example, the above binary watch reads “3:25”.

Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times 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 not matter.
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”.

## 描述

```输入: n = 1

```

### 思路

• 对每个位置编号 （范围是 [0,9]，一共 10 个位置），形成键值对；键位编号，值表盘对应的时间。
• 其中，对分钟用 range(0,6) 进行编号；小时用 range(6,10) 进行编号；
• 对于输入 num，使用 Python 的 combinations 模块，从 list(range(10)) 中随机选取 num 个数字；然后以这些数字为键，拿到对应的小时和分钟数，构成当前时间；对于不符合要求的时间直接丢弃；
```# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-09-03 22:35:31
# @Last Modified by:   何睿
# @Last Modified time: 2019-09-04 08:59:55

from typing import List
from itertools import combinations

class Solution:
def readBinaryWatch(self, num: int) -> List[str]:
minutes = {i: 2**i for i in range(6)}
hours = {i: 2**(i - 6) for i in range(6, 10)}
times = map(lambda x: self.__transfer(x, minutes, hours), combinations(list(range(10)), num))

return filter(lambda x: x is not None, times)

def __transfer(self, com, minutes, hours):
minute = sum(map(lambda x: minutes.get(x, 0), com))
hour = sum(map(lambda x: hours.get(x, 0), com))

return "{}:{:02d}".format(hour, minute) if hour <= 11 and minute <= 59 else None

```

©本文是原创文章，欢迎转载，转载需保留 文章来源 ，作者信息和本声明.

Posted in LeetCode and tagged , .

### 何 睿

This site uses Akismet to reduce spam. Learn how your comment data is processed.