VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-bits-number-count-consecutive-set-bits-increasing-order/

⇱ Check if bits of a number has count of consecutive set bits in increasing order - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 11 Sep, 2023

Given a integer n > 0, the task is to find whether in the bit pattern of integer count of continuous 1's are in increasing from left to right. 

Examples : 

Input:19
Output:Yes
Explanation: Bit-pattern of 19 = 10011,
Counts of continuous 1's from left to right 
are 1, 2 which are in increasing order.

Input : 183
Output : yes
Explanation: Bit-pattern of 183 = 10110111,
Counts of continuous 1's from left to right 
are 1, 2, 3 which are in increasing order.

A simple solution is to store binary representation of given number into a string, then traverse from left to right and count the number of continuous 1's. For every encounter of 0 check the value of previous count of continuous 1's to that of current value, if the value of previous count is greater than the value of current count then return False, Else when string ends return True. 


Output : 
Yes

 

Time Complexity: O(logn)

Auxiliary Space: O(logn)

An efficient solution is to use decimal to binary conversion loop that divides number by 2 and take remainder as bit. This loop finds bits from right to left. So we check if right to left is in decreasing order or not. 

Below is the implementation.  


Output : 
No

 

Time Complexity: O(log2n)

Auxiliary Space: O(1)


 

Comment
Article Tags:
Article Tags: