
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 c_cnt < p_cnt, then
- if bits_pattern[i] is same as 1, then
- 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
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
- Related Articles
- Check if all bits of a number are set in Python
- Check if a number has two adjacent set bits in C++
- Check if a number has same number of set and unset bits in C++
- Check if a number has bits in alternate pattern - Set 1 in C++
- Python Count set bits in a range?
- Check whether the number has only first and last bits set in Python
- Check if a number has bits in alternate pattern - Set-2 O(1) Approach in C++
- Count unset bits of a number in C++
- C# program to count total set bits in a number
- Prime Number of Set Bits in Binary Representation in Python
- Count set bits using Python List comprehension
- Program to count operations to remove consecutive identical bits in Python
- Count set bits in a range in C++
- Python Program to Count set bits in an integer
- Number of 1 Bits in Python

Advertisements