Length of the Longest Consecutive 1s in Binary Representation

10 Jun, 2022
Given a number n, find length of the longest consecutive 1s in its binary representation.Examples : 
Input : n = 14
Output : 3
The binary representation of 14 is 1110.

Input : n = 222
Output : 4
The binary representation of 222 is 11011110.
Naive Approach: One simple way would be to simply loop over the bits, and keep track of the number of consecutive set bits, and the maximum that this value has reached. In this approach, we need to convert it to binary (base-2) representation and then find and print the result.
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
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.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find length of the longest// consecutive 1s in binary representation of// a number.#include<bits/stdc++.h>using namespace std; 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;} // Driver codeint main(){    cout << maxConsecutiveOnes(14) << endl;    cout << maxConsecutiveOnes(222) << endl;    return 0;}
// Java program to find length of the longest// consecutive 1s in binary representation of// a number.class MaxConsecutiveOnes{    private static 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;    }     // Driver code    public static void main(String strings[])    {        System.out.println(maxConsecutiveOnes(14));        System.out.println(maxConsecutiveOnes(222));    }}
# Python program to find# length of the longest# consecutive 1s in# binary representation of# a number. def maxConsecutiveOnes(x):     # Initialize result    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=count+1         return count # Driver code print(maxConsecutiveOnes(14))print(maxConsecutiveOnes(222)) # This code is contributed# by Anant Agarwal.
// C# program to find length of the// longest consecutive 1s in binary// representation of a number.using System; class GFG {         // Function to find length of the    // longest consecutive 1s in binary    // representation of a number    private static 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;    }     // Driver code    public static void Main()    {        Console.WriteLine(maxConsecutiveOnes(14));        Console.Write(maxConsecutiveOnes(222));    }} // This code is contributed by Nitin Mittal.
<?php// PHP program to find length// of the longest consecutive// 1s in binary representation of// a number. function maxConsecutiveOnes($x){    // Initialize result    $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;} // Driver codeecho maxConsecutiveOnes(14), "\n";echo maxConsecutiveOnes(222), "\n"; // This code is contributed by Ajit?>
<script> // Javascript program to find length// of the longest consecutive 1s in// binary representation of a number.function maxConsecutiveOnes(x){         // Initialize result    let 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;} // Driver codedocument.write(maxConsecutiveOnes(14) + "<br/>");document.write(maxConsecutiveOnes(222)); // This code is contributed by code_hunt    </script>
Output : 
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
3
4
Time Complexity: O(log x)
Auxiliary Space: O(1)
Length of the Longest Consecutive 1s in Binary Representation | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersLength of the Longest Consecutive 1s in Binary Representation | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:14•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=X06Vml-8X8A" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
 
This article is contributed by Pankaj Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.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. 
nitin mittal
jit_t
code_hunt
abhishek0719kadiyan
subhammahato348
technophpfij
binary-representation
MAQ Software
Bit Magic
MAQ Software
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.