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.
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.
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.
This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Check if all bits can be made same by flipping two consecutive bits
- Check if all bits of a number are set
- Check whether the number has only first and last bits set | Set 2
- Check whether the number has only first and last bits set
- Toggle bits of a number except first and last bits
- Count pairs (A, B) such that A has X and B has Y number of set bits and A+B = C
- Count total bits in a number
- Count unset bits of a number
- Count Set-bits of number using Recursion
- Check if a number has two adjacent set bits
- Count of pairs in an Array with same number of set bits
- Count number of bits to be flipped to convert A to B | Set-2
- Count number of bits to be flipped to convert A to B
- Count pairs of elements such that number of set bits in their AND is B[i]
- Program to count number of set bits in an (big) array