[LeetCode] Challenge log 401

401. Binary Watch

https://leetcode.com/problems/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:

1
2
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”.
Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# cache all (number of leds, mins/hours} in dict
# check all combination
class Solution:
def readBinaryWatch(self, num):
"""
:type num: int
:rtype: List[str]
"""
hours = {}
for i in range(12):
numberOfLed = bin(i).count('1')
if numberOfLed not in hours:
hours[numberOfLed] = [str(i)]
else:
hours[numberOfLed].append(str(i))
print(hours)
mins = {}
for i in range(60):
if i >= 10:
temp = str(i)
else:
temp = '0' + str(i)
numberOfLed = bin(i).count('1')
if numberOfLed not in mins:
mins[numberOfLed] = [temp]
else:
mins[numberOfLed].append(temp)
print(mins)

results = []
for h in range(num+1):
m = num - h
if m in mins and h in hours:
results = results + [ hh + ':' + mm for hh in hours[h] for mm in mins[m]]

return results
1
2
3
4
5
6
7
8
9
# same idea but 200% neater
class Solution:
def readBinaryWatch(self, num):
"""
:type num: int
:rtype: List[str]
"""
return ["{}:{:0>2d}".format(i,j) for i in range(12) for j in range(60) \
if bin(i).count('1') + bin(j).count('1') == num]
0%