📌  相关文章
📜  小于N的最大数M,使得M和N的XOR为偶数

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

给定正整数N ,任务是找到最大整数M ,以使0 <= M XOR(M,N)为偶数。如果对于给定的N无法获得M的值,则打印-1

例子:

方法:
解决问题时需要进行以下观察:

  • 以二进制形式表示的奇数以1作为其最低有效位(LSB),而以二进制形式表示的偶数以0作为其最低有效位(LSB)。
  • 在执行XOR操作时,如果设置的位数为奇数,则XOR值为1。如果设置的位数为偶数,则XOR值为0。
  • 因此,我们需要对两个奇数或两个偶数执行XOR运算,以得到一个偶数。

根据以上说明,可以通过以下步骤解决问题:

  1. 如果N为奇数,则小于N的最大奇数将为N – 2
  2. 如果N为偶数,则小于N的最大偶数将为N – 2
  3. 因此,如果N = 1,则在这种情况下无法获得作为合适的M的打印-1。对于所有其他情况,请打印N – 2作为请求者。

下面是上述方法的实现:

C++
// C++ program for the above problem.
#include 
using namespace std;
 
// Function to find the maximum
// possible value of M
int getM(int n)
{
    // Edge case
    if (n == 1)
        return -1;
 
    // M = N - 2 is maximum
    // possible value
    else
        return n - 2;
}
 
// Driver Code
int main()
{
    int n = 10;
 
    int ans = getM(n);
    cout << ans;
}


Java
// Java program for the above problem.
import java.util.*;
 
class GFG{
     
// Function to find the maximum
// possible value of M
static int getM(int n)
{
     
    // Edge case
    if (n == 1)
        return -1;
             
    // M = N - 2 is maximum
    // possible value
    else
        return n - 2;
}
     
// Driver code
public static void main(String[] args)
{
    int n = 10;
         
    System.out.print(getM(n));
}
}
 
// This code is contributed by sanjoy_62


Python3
# Python3 program for the above problem
 
# Function to find the maximum
# possible value of M
def getM(n):
     
    # Edge case
    if (n == 1):
        return -1;
         
    # M = N - 2 is maximum
    # possible value
    else:
        return n - 2;                
 
# Driver code
n = 10
 
print(getM(n))
 
# This code is contributed by sanjoy_62


C#
// C# program for the above problem.
using System;
class GFG{
     
// Function to find the maximum
// possible value of M
static int getM(int n)
{
     
    // Edge case
    if (n == 1)
        return -1;
                 
    // M = N - 2 is maximum
    // possible value
    else
        return n - 2;
}
 
// Driver code
static void Main()
{
    int n = 10;
         
    Console.Write(getM(n));
}
}
 
// This code is contributed by divyeshrabadiya07


Javascript


输出:
8

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

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。