Given a number n, find length of the longest consecutive 1s in its binary representation.
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.
This article is contributed by Pankaj Kumar. 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.
- Length of longest consecutive zeroes in the binary representation of a number.
- Find consecutive 1s of length >= n in binary representation of a number
- 1 to n bit numbers with no consecutive 1s in binary representation.
- 1 to n bit numbers with no consecutive 1s in binary representation
- Longest common substring in binary representation of two numbers
- Find longest sequence of 1's in binary representation with one flip
- Binary representation of a given number
- Maximum 0's between two immediate 1's in binary representation
- XOR counts of 0s and 1s in binary representation
- Binary representation of next number
- Find value of k-th bit in binary representation
- Binary representation of previous number
- Next greater number than N with exactly one bit different in binary representation of N
- Largest number with binary representation is m 1's and m-1 0's
- Count numbers have all 1s together in binary representation