Given an integer N, the task is to find the smallest integer X such that it has no odd position set and X ≥ N.
Note: The positioning of bits is assumed from the right side and the first bit is assumed to be 0th bit.
Input: N = 9
16’s binary representation is 10000, which has its 4th bit
set which is the smallest number possible satisfying the given condition.
Input: N = 5
Input: N = 19
Approach: The problem can be solved using a greedy approach and some bit properties. The property that if smaller powers of two are taken exactly once and added up they can never exceed a higher power of two (e.g., (1 + 2 + 4) < 8). The following greedy approach is used to solve the above problem:
- Initially count the number of bits.
- Get the leftmost index of the set bit.
- If the leftmost set bit is at an odd index, then answer will always be (1 << (leftmost_bit_index + 1)).
- Else, greedily form a number by setting all the even bits from 0 to leftmost_bit_index. Now greedily remove a power of two from right to check if we get a number which satisfies the given conditions.
- If the above condition does not give us our number, then we simply set the next leftmost even bit and return the answer.
Below is the implementation of the above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Find smallest number n such that n XOR n+1 equals to given k.
- Smallest number greater than or equal to N divisible by K
- Smallest Special Prime which is greater than or equal to a given number
- Smallest number greater than n that can be represented as a sum of distinct power of k
- Smallest number greater than or equal to X whose sum of digits is divisible by Y
- Smallest divisor D of N such that gcd(D, M) is greater than 1
- Smallest power of 4 greater than or equal to N
- Length of Smallest subarray in range 1 to N with sum greater than a given value
- Highest and Smallest power of K less than and greater than equal to N respectively
- Smallest integer greater than n such that it consists of digit m exactly k times
- Minimum number of squares whose sum equals to given number N | set 2
- Minimum number of squares whose sum equals to given number n
- Find the number of pairs such that their gcd is equals to 1
- Number of Co-prime pairs from 1 to N with product equals to N
- Check whether all the rotations of a given number is greater than or equal to the given number or not
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.