Given an integer N, the task is to find whether the bits of N can be arranged in alternating manner i.e. either 0101… or 10101…. Assume that N is represented as a 32 bit integer.
Input: N = 23
“00000000000000000000000000010111” is the binary representation of 23
and the required permutation of bits is not possible.
Input: N = 524280
binary(524280) = “00000000000001111111111111111000” which can be
rearranged to “01010101010101010101010101010101”.
Approach: Since the given integer has to be represented in 32 bits and the number of 1s must be equal to the number of 0s in its binary representation to satisfy the given condition. So, the number of set bits in N must be 16 which can be easily calculated using __builtin_popcount()
Below is the implementation of the above approach:
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.
- Minimum number of given operations required to convert a permutation into an identity permutation
- Minimum number of adjacent swaps required to convert a permutation to another permutation by given condition
- Find the permutation of first N natural numbers such that sum of i % Pi is maximum possible
- Check if bits of a number has count of consecutive set bits in increasing order
- Toggle bits of a number except first and last bits
- Check if all bits can be made same by flipping two consecutive bits
- Print numbers having first and last bits as the only set bits
- Iterating over all possible combinations in an Array using Bits
- Find smallest permutation of given number
- Find a permutation such that number of indices for which gcd(p[i], i) > 1 is exactly K
- Find permutation of n which is divisible by 3 but not divisible by 6
- Find a permutation of 2N numbers such that the result of given expression is exactly 2K
- Find the good permutation of first N natural numbers
- Find the number of sub arrays in the permutation of first N natural numbers such that their median is M
- Find permutation of first N natural numbers that satisfies the given condition
- Find the permutation p from the array q such that q[i] = p[i+1] - p[i]
- Find permutation with maximum remainder Sum
- Find permutation array from the cumulative sum array
- Find the minimum permutation of A greater than B
- Find the K-th Permutation Sequence of first N natural numbers
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.