Length of the Longest Consecutive 1s
Interview
Description:
Given a number n, find length of the longest consecutive 1s in its binary representation.
Example:
Input : n = 14
Output : 3
The binary representation of 14 is 1110.
Input : n = 222
Output : 4
The binary representation of 222 is 11011110.
Idea:
Using Bit Magic: The idea is based on the concept that if we AND a bit sequence with a shifted version of itself, we’re effectively removing the trailing 1 from every sequence of consecutive 1s.
11101111 (x)
& 11011110 (x << 1)
----------
11001110 (x & (x << 1))
^ ^
| |
trailing 1 removed
Time: O(k), k is the longest 1s.
Code:
int maxConsecutiveOnes(int x)
{
// Initialize result
int count = 0;
// Count the number of iterations to
// reach x = 0.
while (x!=0)
{
// This operation reduces length
// of every sequence of 1s by one.
x = (x & (x << 1));
count++;
}
return count;
}