![]() |
VOOZH | about |
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.
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.
No
Time Complexity: O(log2n)
Auxiliary Space: O(1)