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

📅  最后修改于: 2021-04-29 15:51:24             🧑  作者: Mango

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

例子:

天真的方法:天真的解决方案是运行一个从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