Check if the binary representation of a number has equal number of 0s and 1s in blocks in Python


Suppose we have a number num, we have to check whether the binary representation of num has the same number of consecutive blocks of 0s and 1s. We have to keep in mind that 0 and a number with all 1s are not considered to have number of blocks of 0s and 1s.

So, if the input is like num = 455, then the output will be True, as the binary representation of this number is 111000111.

To solve this, we will follow these steps −

  • bin_form := binary form of num
  • one_count := a new set
  • count := 1
  • for i in range 0 to bit count of bin_form - 1, do
    • if bin_form[i] is same as bin_form[i + 1], then
      • count := count + 1
    • otherwise,
      • insert count into one_count
      • count := 1
  • if size of one_count is same as 1, then
    • return True
  • return False

Let us see the following implementation to get better understanding −

Example Code

Live Demo

def solve(num):
   bin_form = bin(num).replace("0b", "")
   one_count = set()
   count = 1
 
   for i in range(len(bin_form)-1):
      if bin_form[i] == bin_form[i + 1]:
         count += 1
      else:
         one_count.add(count)
         count = 1
 
   if len(one_count) == 1:
      return True
   return False
 
num = 455
print(solve(num))

Input

455

Output

True

Updated on: 15-Jan-2021

151 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements