2nd LeetCode: readBinaryWatch
The second LeetCode demand us to calculate all the possible time display by n bits on in a digital binary watch. The watch has 10 bits to display time. The hour was displayed by summation of 4 bits, representing 8,4,2,1, and the minute was displayed by summation of 6 bits, representing 32,16,8,4,2,1.
The watch looks like this:
hr digit:8 4 2 1
hr light:0 0 1 0
(8*0+4*0+2*1+1*0: hr=2)
min digit:32 16 8 4 2 1
min light: 0 0 0 1 10
(32*0+16*0+8*0+4*1+2*1+1*0: min=6)
=>represent 2:06
In the case above, 3 digits was on.
The guideline of this problem:
1. List the possibility of choosing n bits in 10 bits.
2. Transform those possibilities into time “H(or HH): MM”.
from itertools import combinations
class Solution:
def readBinaryWatch(self, num: int) -> list:
# List the digit numbers
#hr: bit 4~9, 4th for 32
#min: bit 0~3, 0th for 8
m=[0,1,2,3,4,5,6,7,8,9]
# Initialize the list of times
List=[]
# Special condition: 0 digits on represent 0:00
if num==0:
return ["0:00"]
# For each combination of num out of 10 digits
for ii in combinations(m,num):
# If the min exceed 59, skip the combination
if 7 in ii and 6 in ii and 5 in ii and 4 in ii: continue
# If the hr exceed 11, skip the combination
if 0 in ii and 1 in ii: continue
# Create a blank argument full of zero
ar = [0,0,0,0,0,0,0,0,0,0]
for jj in ii:
# Fill in "1"s if the digit is picked in the combination
ar[jj]=1
# Calculate the represented time
mmin = 1 * ar[9] + 2 * ar[8] + 4 * ar[7] + 8 * ar[6] + 16 * ar[5] + 32 * ar[4]
hhr = 1 * ar[3] + 2 * ar[2] + 4 * ar[1] + 8 * ar[0]
# Transform into the assigned form of time
List.append(str(hhr)+":"+"0"*(mmin < 10)+str(mmin))
return List