Skip to content

Commit b2fe8aa

Browse files
authored
Create binary-watch.py
1 parent 5409b86 commit b2fe8aa

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Python/binary-watch.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Time: O(1)
2+
# Space: O(1)
3+
4+
# A binary watch has 4 LEDs on the top which represent the hours (0-11),
5+
# and the 6 LEDs on the bottom represent the minutes (0-59).
6+
#
7+
# Each LED represents a zero or one, with the least significant bit on the right.
8+
#
9+
# For example, the above binary watch reads "3:25".
10+
#
11+
# Given a non-negative integer n which represents the number of LEDs that are currently on,
12+
# return all possible times the watch could represent.
13+
#
14+
# Example:
15+
#
16+
# Input: n = 1
17+
# Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]
18+
# Note:
19+
# The order of output does not matter.
20+
# The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00".
21+
22+
23+
class Solution(object):
24+
def readBinaryWatch(self, num):
25+
"""
26+
:type num: int
27+
:rtype: List[str]
28+
"""
29+
def bit_count(bits):
30+
count = 0
31+
while bits:
32+
bits &= bits-1
33+
count += 1
34+
return count
35+
36+
return ['%d:%02d' % (h, m)
37+
for h in xrange(12) for m in xrange(60)
38+
if bit_count(h) + bit_count(m) == num]

0 commit comments

Comments
 (0)