Binary Prefix Divisible By 5 in Python


Suppose we have an array A of 0s and 1s, consider N[i] is the i-th subarray from index A[0] to A[i] interpreted as a binary number. We have to find a list of boolean answers, where answer[i] is true if and only if N[i] is divisible by 5.

So, if the input is like [0,1,1,1,1,1], then the output will be [true,false,false,false,true,false]

To solve this, we will follow these steps −

  • length := size of A
  • ans:= make an array of size length, and fill with false
  • number:= a binary value by concatenating each element from A
  • for i in range 0 to length, do
    • if number mod 5 is same as 0, then
      • ans[length-i-1] := True
    • number:= number / 2
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def prefixesDivBy5(self, A):
      length=len(A)
      ans=[False]*length
      number=int("".join(map(str,A)),2)
      for i in range(length):
         if number%5==0:
            ans[length-i-1]=True
            number=number>>1
      return ans
ob = Solution()
print(ob.prefixesDivBy5([0,1,1,1,1,1]))

Input

[0,1,1,1,1,1]

Output

[True, False, False, False, True, False]

Updated on: 06-Jul-2020

100 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements