Given a number N, the task is to find the maximum distance between two 1’s in the binary representation of given N. Print -1 if binary representation contains less than two 1’s.
Input: N = 131 Output: 6 131 in binary = 10000011. The maximum distance between two 1's = 6. Input: N = 8 Output: -1 8 in binary = 01000. It contains less than two 1's.
- First find the binary representation of N.
- For each bit calculated, check if its a ‘1’.
- Store the index of first ‘1’ found in first_1, and the last ‘1’ found in last_1
- Then check if the last_1 is less than or equal to first_1. It will be the case when N is a power of 2. Hence print -1 in this case.
- In any other case, find the difference between the last_1 and first_1. This will be the required distance.
Below is the implementation of the above approach:
6 -1 3 4
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Maximum 0's between two immediate 1's in binary representation
- Maximum distance between two 1s in a Binary Array in a given range
- Distance of chord from center when distance between center and another equal length chord is given
- Find the occurrence of the given binary pattern in the binary representation of the array elements
- Distance between two nodes of binary tree with node values from 1 to N
- Queries to find distance between two nodes of a Binary tree - O(logn) method
- Maximum number of consecutive 1's in binary representation of all the array elements
- Longest common substring in binary representation of two numbers
- Number of mismatching bits in the binary representation of two integers
- Maximum distance between two elements whose absolute difference is K
- Check if binary representation of a number is palindrome
- Decimal representation of given binary string is divisible by 5 or not
- Find longest sequence of 1's in binary representation with one flip
- Binary representation of next number
- Check if binary representation of a given number and its complement are anagram
- 1 to n bit numbers with no consecutive 1s in binary representation.
- Binary representation of previous number
- Prime Number of Set Bits in Binary Representation | Set 2
- Decimal representation of given binary string is divisible by 10 or not
- Largest number with binary representation is m 1's and m-1 0's
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.