Binary Prefix Divisible By 5
The key to this problem is understanding how to build up the binary representation incrementally, which is analogous to calculating the value of a number in base10 from its digit representation.
Here is how we can approach this problem:
Initialize a variable, say
num
, to 0. This variable will store the running value of the binary number as we traverse thenums
array.Create a list
res
to store the boolean results.For each bit in
nums
, we shift the current value ofnum
to the left (which is equivalent to multiplyingnum
by 2 in decimal) and then add the current bit. This operation will construct the numberxi
bit by bit.Check if the current number
num
is divisible by 5. If it is, appendTrue
tores
, otherwise appendFalse
.Since
num
can grow large due to left shift, and we only care about whether it’s divisible by 5, we can take a modulus by 5 at each step to keepnum
manageable.
Python solution:


In this code, we iterate over the input list nums
and build up the number num
bit by bit. The expression (num << 1) + i
calculates the current value of num
, and the modulus operator % 5
ensures that num
doesn’t grow too large. The result of the divisibility test num == 0
is appended to the res
list. The function returns the res
list, which is the desired output.