Given two number A and K, the task is to find K’th smallest positive integer B such that A + B = A | B, where | denotes the bitwise OR operator.
Input: A = 10, K = 3 Output: 5 Explanation: K = 1, 10 + 1 = 10 | 1 = 11 K = 2, 10 + 4 = 10 | 4 = 14 K = 3, 10 + 5 = 10 | 5 = 15 Input: A = 1, B = 1 Output: 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 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.
Below is the implementation of the above approach:
Time Complexity: O(log(n))
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.