📜  按位与为正的前 N 个自然数的最大数集

📅  最后修改于: 2022-05-13 01:56:08.089000             🧑  作者: Mango

按位与为正的前 N 个自然数的最大数集

给定一个正整数N ,任务是从按位与为正的前N个自然数中找到最大的数字集

例子:

方法:可以根据2 N和 (2 N – 1)导致0的观察来解决给定的问题。因此,集合的最大长度不能在同一集合中同时包含2 N和 (2 N – 1) 。具有非零 AND 值的最大子数组可以找到为:

  • 求 2 小于或等于N的最大幂,如果N是 2 的幂,则答案应为N/2 ,例如,当 N 为16时,AND 值非零的最大子数组为8
  • 否则,答案是N与小于或等于N的 2 的最大幂之间的长度。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the maximum set of
// number whose Bitwise AND is positive
int maximumSizeOfSet(int N)
{
    // Base Case
    if (N == 1)
        return 1;
 
    // Store the power of 2 less than
    // or equal to N
    int temp = 1;
    while (temp * 2 <= N) {
        temp *= 2;
    }
 
    // N is power of 2
    if (N & (N - 1) == 0)
        return N / 2;
    else
        return N - temp + 1;
}
 
// Driver Code
int main()
{
    int N = 7;
    cout << maximumSizeOfSet(N);
 
    return 0;
}


Java
// Java program for the above approach
class GFG{
 
// Function to find the maximum set of
// number whose Bitwise AND is positive
public static int maximumSizeOfSet(int N)
{
   
    // Base Case
    if (N == 1)
        return 1;
 
    // Store the power of 2 less than
    // or equal to N
    int temp = 1;
    while (temp * 2 <= N) {
        temp *= 2;
    }
 
    // N is power of 2
    if ((N & (N - 1)) == 0)
        return N / 2;
    else
        return N - temp + 1;
}
 
// Driver Code
public static void main(String args[])
{
    int N = 7;
    System.out.println(maximumSizeOfSet(N));
}
 
}
 
// This code is contributed by gfgking.


Python3
# python program for the above approach
 
# Function to find the maximum set of
# number whose Bitwise AND is positive
def maximumSizeOfSet(N):
 
    # Base Case
    if (N == 1):
        return 1
 
    # Store the power of 2 less than
    # or equal to N
    temp = 1
    while (temp * 2 <= N):
        temp *= 2
 
    # N is power of 2
    if (N & (N - 1) == 0):
        return N // 2
    else:
        return N - temp + 1
 
# Driver Code
if __name__ == "__main__":
 
    N = 7
    print(maximumSizeOfSet(N))
 
# This code is contributed by rakeshsahni


C#
// C# program for the above approach
using System;
 
public class GFG {
 
    static int maximumSizeOfSet(int N)
    {
 
        // Base Case
        if (N == 1)
            return 1;
 
        // Store the power of 2 less than
        // or equal to N
        int temp = 1;
        while (temp * 2 <= N) {
            temp *= 2;
        }
 
        // N is power of 2
        if ((N & (N - 1)) == 0)
            return N / 2;
        else
            return N - temp + 1;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int N = 7;
 
        Console.WriteLine(maximumSizeOfSet(N));
    }
}
 
// This code is contributed by dwivediyash


Javascript


输出:
4

时间复杂度: O(log N)
辅助空间: O(1)