📌  相关文章
📜  M的最大可能值,不超过N,且它们之间的按位OR和XOR相等

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

给定整数N ,任务是找到最大的数M ,其中( M ),使得N(XOR)M等于N(OR)M,(N ^ M)=(N | M)

例子:

方法:
要获得所需的数字M ,请从N的最低有效位(LSB)到最高有效位(MSB)遍历N的所有位。这里出现两种情况:

  1. 如果N第i1,则:
    • 如果Mi比特被设置为1,N ^ M将不等于N | M(1 ^ 1 = 0)(1 | 1 = 1)。
    • 如果i被设置M的为0,N ^ M将等于N | M(1 ^ 0 = 1)(1 | 0 = 1)。
    • 因此,如果N第i1,Mi比特设置为0。
  2. 如果N第i0,则:
    • 如果Mi比特被设置为1,N ^ M将等于N | M(0 ^ 1 = 1)(0 | 1 = 1)。
    • 如果我们Mi比特设置为0,N ^ M将等于N | M(0 ^ 0 = 0)(0 | 0 = 0)。
    • 因此,如果Mi比特被设置为01,N ^ M将总是等于N | M。
    • 由于必须找出小于NM的最大值,因此始终将M的i位设置为1

下面是上述方法的实现:

C++
// C++ Program to implement
// the above approach
#include 
using namespace std;
 
// Function to find required
// number M
int equalXORandOR(int n)
{
    // Initialising m
    int m = 0;
 
    // Finding the index of the
    // most significant bit of N
    int MSB = (int)log2(n);
 
    // Calculating required number
    for (int i = 0; i <= MSB; i++) {
 
        if (!(n & (1 << i))) {
            m += (1 << i);
        }
    }
 
    return m;
}
 
// Driver Code
int main()
{
    int n = 14;
    cout << equalXORandOR(n);
    return 0;
}


Java
// Java program to implement
// the above approach
class GFG{
 
// Function to find required
// number M
static int equalXORandOR(int n)
{
     
    // Initialising m
    int m = 0;
 
    // Finding the index of the
    // most significant bit of N
    int MSB = (int)Math.log(n);
 
    // Calculating required number
    for(int i = 0; i <= MSB; i++)
    {
        if ((n & (1 << i)) <= 0)
        {
            m += (1 << i);
        }
    }
    return m;
}
 
// Driver Code
public static void main(String[] args)
{
    int n = 14;
     
    System.out.print(equalXORandOR(n));
}
}
 
// This code is contributed by amal kumar choubey


Python3
# Python3 program to implement
# the above approach
from math import log2
 
# Function to find required
# number M
def equalXORandOR(n):
 
    # Initialising m
    m = 0
 
    # Finding the index of the
    # most significant bit of N
    MSB = int(log2(n))
 
    # Calculating required number
    for i in range(MSB + 1):
        if(not(n & (1 << i))):
            m += (1 << i)
 
    return m
 
# Driver Code
n = 14
 
# Function call
print(equalXORandOR(n))
 
# This code is contributed by Shivam Singh


C#
// C# program to implement
// the above approach
using System;
 
class GFG{
 
// Function to find required
// number M
static int equalXORandOR(int n)
{
     
    // Initialising m
    int m = 0;
 
    // Finding the index of the
    // most significant bit of N
    int MSB = (int)Math.Log(n);
 
    // Calculating required number
    for(int i = 0; i <= MSB; i++)
    {
        if ((n & (1 << i)) <= 0)
        {
            m += (1 << i);
        }
    }
    return m;
}
 
// Driver Code
public static void Main(String[] args)
{
    int n = 14;
     
    Console.Write(equalXORandOR(n));
}
}
 
// This code is contributed by amal kumar choubey


Javascript


输出:
1

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