📌  相关文章
📜  设置最多 K 位的最小整数,使得它们与 N 的按位 AND 最大

📅  最后修改于: 2021-10-25 11:22:05             🧑  作者: Mango

给定一个可以用 32 位表示的整数N ,任务是找到另一个整数X ,在其二进制表示中最多设置 K 位,并且XN 的按位 AND 最大。

例子:

朴素的方法:朴素的解决方案是从 1 到 N 运行一个循环,并与 N 进行按位与,并检查设置的位数是否小于或等于 K。在每次迭代期间保持按位与的最大值。
时间复杂度: O(N)

高效方法:这个问题可以通过对位使用贪婪方法来有效解决。因为 N 最多可以有 32 位。所以我们将从最高位开始遍历并检查它是否在 N 中被设置(或 1),如果它没有被设置那么就没有必要设置这个位,因为 AND 操作会使它在最终答案中为零,否则我们将把它设置在我们要求的答案中。此外,我们将在每次迭代中维护设置位的计数并检查它是否不超过 K。
时间复杂度: O(32)

以下是上述有效方法的实现:

C++
// C++ program for the
// above approach
#include 
using namespace std;
 
// Function to find
// the integer with
// maximum bitwise with N
int find_max(int n, int k)
{
  // Store answer in the bitset
  // Initialized with 0
  bitset<32> X(0);
 
  // To maintain the count
  // of set bits that should
  // exceed k
  int cnt = 0;
 
  // Start traversing from the
  // Most significantif that bit
  // is set in n then we will set
  // in our answer i.e in X
  for (int i = 31; i >= 0 &&
           cnt != k; i--)
  {
    // Checking if the ith bit
    // is set in n or not
    if (n & (1 << i))
    {
      X[i] = 1;
      cnt++;
    }
  }
 
  // Converting into integer
  return X.to_ulong();
}
 
// Driver Code
int main()
{
  int n = 10, k = 2;
 
  // Function Call
  cout << find_max(n, k) <<
          endl;
 
  return 0;
}


Java
// Java program for the
// above approach
import java.util.*;
import java.lang.*;
class GFG{
 
// Function to find
// the integer with
// maximum bitwise with N
static int find_max(int n,
                    int k)
{
  // Store answer in the
  // bitset Initialized
  // with 0
  int[] X = new int[32];
 
  // To maintain the count
  // of set bits that should
  // exceed k
  int cnt = 0;
 
  // Start traversing from the
  // Most significant if that bit
  // is set in n then we will set
  // in our answer i.e in X
  for (int i = 31; i >= 0 &&
           cnt != k; i--)
  {
    // Checking if the ith bit
    // is set in n or not
    if ((n & (1 << i)) != 0)
    {
      X[i] = 1;
      cnt++;
    }
  }
 
  String s = "";
  for(int i = 31; i >= 0; i--)
    s += X[i] == 0 ? '0' : '1';
 
  // Converting into integer
  return Integer.parseInt(s,2);
}
 
// Driver function
public static void main (String[] args)
{
  int n = 10, k = 2;
 
  // Function Call
  System.out.println(find_max(n, k));
}
}
 
// This code is contributed by offbeat


Python3
# Python3 program for the above approach
 
# Function to find the integer with
# maximum bitwise with N
def find_max(n, k):
     
    # Store answer in the
    # bitset Initialized
    # with 0
    X = [0] * 32
     
    # To maintain the count
    # of set bits that should
    # exceed k
    cnt = 0
     
    # Start traversing from the
    # Most significant if that bit
    # is set in n then we will set
    # in our answer i.e in X
    i = 31
     
    while (i >= 0 and cnt != k):
         
        # Checking if the ith bit
        # is set in n or not
        if ((n & (1 << i)) != 0):
            X[i] = 1
            cnt += 1
             
        i -= 1
     
    s = ""
     
    for i in range(31, -1, -1):
        if X[i] == 0:
            s += '0'
        else:
            s += '1'
     
    # Converting into integer
    return int(s, 2)
     
# Driver code
n, k = 10, 2
 
# Function Call
print(find_max(n, k))
 
# This code is contributed by divyeshrabadiya07


C#
// C# program for the above approach
using System;
 
class GFG{
     
// Function to find the integer with
// maximum bitwise with N
static int find_max(int n, int k)
{
     
    // Store answer in the
    // bitset Initialized
    // with 0
    int[] X = new int[32];
     
    // To maintain the count
    // of set bits that should
    // exceed k
    int cnt = 0;
     
    // Start traversing from the
    // Most significant if that bit
    // is set in n then we will set
    // in our answer i.e in X
    for(int i = 31; i >= 0 && cnt != k; i--)
    {
         
        // Checking if the ith bit
        // is set in n or not
        if ((n & (1 << i)) != 0)
        {
            X[i] = 1;
            cnt++;
        }
    }
     
    String s = "";
     
    for(int i = 31; i >= 0; i--)
        s += X[i] == 0 ? '0' : '1';
     
    // Converting into integer
    return Convert.ToInt32(s, 2);
}
 
// Driver code
public static void Main(String[] args)
{
    int n = 10, k = 2;
     
    // Function Call
    Console.Write(find_max(n, k));
}
}
 
// This code is contributed by offbeat


Javascript


输出
10

性能分析:

  • 时间复杂度: O(32)
  • 辅助空间: O(1

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程