Check if bits of a number has count of consecutive set bits in increasing order in Python


Suppose we have a positive number n, we have to check whether in the bit pattern of the given number n the count of continuous 1s are increasing from left to right or not.

So, if the input is like n = 1775, then the output will be True, as the binary representation of n is 11011101111, so number of continuous 1s are [2, 3, 4] which are increasing

To solve this, we will follow these steps −

  • bits_pattern := a new list of bits of n
  • bit_count := size of bits_pattern
  • p_cnt := 0, c_cnt := 0
  • i := 0
  • while i < bit_count, do
    • if bits_pattern[i] is same as 1, then
      • c_cnt := c_cnt + 1, i := i + 1
    • otherwise when bits_pattern[i - 1] is 0, then
      • i := i + 1, c_cnt := 0
      • go for next iteration
    • otherwise,
      • if c_cnt < p_cnt, then
        • return 0
      • i := i + 1, p_cnt := c_cnt, c_cnt := 0
  • if p_cnt > c_cnt and c_cnt is not 0, then
    • return False
  • return True

Let us see the following implementation to get better understanding −

Example

 Live Demo

def solve(n):
   bits_pattern = list(bin(n))
   bit_count = len(bits_pattern)
   p_cnt = 0
   c_cnt = 0
   i = 0
   while i < bit_count:
      if bits_pattern[i] == '1':
         c_cnt += 1
         i += 1
      elif bits_pattern[i - 1] == '0':
         i += 1
         c_cnt = 0
         continue
      else:
         if c_cnt < p_cnt:
            return 0
            i += 1
            p_cnt = c_cnt
            c_cnt = 0
      if p_cnt > c_cnt and c_cnt != 0:
         return False
   return True
n = 1775
print(solve(n))

Input

1775

Output

True

Updated on: 30-Dec-2020

224 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements