Given a number n, the task is to find the maximum 0’s between two immediate 1’s in binary representation of given n. Return -1 if binary representation contains less than two 1’s.
Input : n = 47 Output: 1 // binary of n = 47 is 101111 Input : n = 549 Output: 3 // binary of n = 549 is 1000100101 Input : n = 1030 Output: 7 // binary of n = 1030 is 10000000110 Input : n = 8 Output: -1 // There is only one 1 in binary representation // of 8.
The idea to solve this problem is to use shift operator. We just need to find the position of two immediate 1’s in binary representation of n and maximize the difference of these position.
- Return -1 if number is 0 or is a power of 2. In these cases there are less than two 1’s in binary representation.
- Initialize variable prev with position of first right most 1, it basically stores the position of previously seen 1.
- Now take another variable cur which stores the position of immediate 1 just after prev.
- Now take difference of cur – prev – 1, it will be the number of 0’s between to immediate 1’s and compare it with previous max value of 0’s and update prev i.e; prev=cur for next iteration.
- Use auxiliary variable setBit, which scans all bits of n and helps to detect if current bits is 0 or 1.
- Initially check if N is 0 or power of 2.
Below is the implementation of the above idea :
This article is contributed by Shashank Mishra ( Gullu ). 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.
- Find the occurrence of the given binary pattern in the binary representation of the array elements
- Binary representation of next number
- XOR counts of 0s and 1s in binary representation
- Find value of k-th bit in binary representation
- Binary representation of a given number
- 1 to n bit numbers with no consecutive 1s in binary representation
- Binary representation of previous number
- 1 to n bit numbers with no consecutive 1s in binary representation.
- 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
- Occurrences of a pattern in binary representation of a number
- Decimal representation of given binary string is divisible by 10 or not
- Decimal representation of given binary string is divisible by 5 or not
- Decimal representation of given binary string is divisible by 20 or not