Given a number a and k, the task is to find the k’th smallest value for b such that a + b = a | b, where ‘|’ denotes the bitwise OR operator. The maximum value of a and k can be .
Input: a = 10, k = 3 Output: 5 Numbers satisfying the condition 5 + b = 5 | b are 1, 4, 5, etc. Since 3rd smallest value for b is required, hence b = 5. Input: a = 1, k = 1 Output: 2 Numbers satisfying the condition 1 + b = 1 | b are 2, 4, 6, etc. Since 1st smallest value for b is required, hence b = 2.
- b is a solution of the given equation if and only if b has 0 in all positions where a has 1 (in binary notation).
- So, we need to determine the bit of b for positions where a has 0. Let, if a = 10100001 then the last eight digits of b must be b = 0*0****0, where ‘*’ denotes either 0 or 1. Any replacement of all ‘*’ by 0 or 1 gives us a solution.
- The k-th smallest number will be received by replacing all ‘*’ in y by digits of binary representation of number k.
- As maximum value of a and k is , so checking upto 32 positions in binary representation is enough to get the correct answer for the given equation.
Below is the implementation of above Approach:
Time Complexity: O(N)
- Find smallest number K such that K % p = 0 and q % K = 0
- Find smallest values of x and y such that ax - by = 0
- Find smallest permutation of given number
- Find smallest number n such that n XOR n+1 equals to given k.
- Find the smallest twins in given range
- Find the kth smallest number with sum of digits as m
- Given a number, find the next smallest palindrome
- Find the k-th smallest divisor of a natural number N
- Find smallest positive number Y such that Bitwise AND of X and Y is Zero
- Find the smallest number X such that X! contains at least Y trailing zeros.
- Program to find the smallest element among three elements
- Find the smallest number with n set and m unset bits
- Find Nth smallest number that is divisible by 100 exactly K times
- Find the lexicographically smallest string which satisfies the given condition
- Find the smallest positive number which can not be represented by given digits
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.