📌  相关文章
📜  求第K个最小数,使得A + B = A |乙

📅  最后修改于: 2021-05-25 07:29:58             🧑  作者: Mango

给定两个数字AK ,任务是找到第K个最小的正整数B,使得A + B = A | B ,其中|表示按位OR运算符。

例子:

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在所有位置A都为1的所有位置都为0时,B才是给定方程的解(以二进制表示)。
  • 因此,我们需要确定A的位置为0的B的位。令,如果A = 10100001,则B的最后八位必须为0_0____0,其中_表示0或1。用_或0替换所有_。 1给我们一个解决方案。
  • 通过用数字k的二进制表示形式的数字替换y中的所有_,将接收第k个最小的数字。

下面是上述方法的实现:

C++
// C++ program for the
// above approach
#include 
using namespace std;
  
// Function to find k'th
// smallest number such that
// A + B = A | B
long long kthSmallest(long long a, long long k)
{
  
    // res will store
    // final answer
    long long res = 0;
    long long j = 0;
  
    for (long long i = 0; i < 32; i++) {
  
        // Skip when j'th position
        // has 1 in binary representation
        // as in res, j'th position will be 0.
        while (j < 32 && (a & (1 << j))) {
            // j'th bit is set
            j++;
        }
  
        // If i'th bit of k is 1
        // and i'th bit of j is 0
        // then set i'th bit in res.
        if (k & (1 << i)) {
            res |= (1LL << j);
        }
  
        // Proceed to next bit
        j++;
    }
  
    return res;
}
  
// Driver Code
int main()
{
  
    long long a = 5, k = 3;
    cout << kthSmallest(a, k) << "\n";
  
    return 0;
}


Python3
# Python3 program for the above approach
  
# Function to find k'th
# smallest number such that 
# A + B = A | B
def kthSmallest(a, k):
  
    # res will store
    # final answer
    res = 0
    j = 0
  
    for i in range(32):
  
        # Skip when j'th position 
        # has 1 in binary representation 
        # as in res, j'th position will be 0.
        while (j < 32 and (a & (1 << j))):
              
            # j'th bit is set
            j += 1
  
        # If i'th bit of k is 1 
        # and i'th bit of j is 0 
        # then set i'th bit in res. 
        if (k & (1 << i)):
            res |= (1 << j)
  
        # Proceed to next bit
        j += 1
  
    return res
  
# Driver Code
a = 5
k = 3
  
print(kthSmallest(a, k))
  
# This code is contributed by himanshu77


输出:
10

时间复杂度: O(log(n))