Length of the Longest Consecutive 1s in Binary Representation

Given a number n, find length of the longest consecutive 1s in its binary representation.
For Example:
Input: n = 100
Output: 2

Explanation: Binary representation of 100 = 1100100
Hence, longest consecutive 1s is 2.
Method 1: The naive solution is to convert the number into its binary form and then loop over the bits, and keep track of the number of consecutive set bits, and the maximum that this value is the required answer.

Method 2: The optimized way 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
So the operation x = (x & (x << 1)) reduces length of every sequence of 1s by one in binary representation of x. If we keep doing this operation in a loop, we end up with x = 0. The number of iterations required to reach 0 is actually length of the longest consecutive sequence of 1s.
#include<bits/stdc++.h>
using namespace std;

int maxConsecutiveOnes(int n)
{
    /* initialize counter */
    int count = 0;

    /* iterate till reached x= 0 */
    while (n!=0)
    {
        /* This operation reduces length
         of every sequence of 1s by one */
        n = (n & (n << 1));

        count++;
    }

    return count;
}

/* driver function */
int main()
{
    cout << maxConsecutiveOnes(100) << endl;
    cout << maxConsecutiveOnes(250) << endl;
    
    return 0;
}
Output:
2
5
Time Complexity: O(number of bits in n)