给定一个正整数N ,任务是找到最大的整数M使得0 <= M < N并且XOR(M, N)是偶数。如果对于给定的N无法获得这样的 M 值,则打印-1 。
例子:
Input: N = 10
Output: 8
Explanation:
(10 XOR 9) = 3, so M = 9 is not possible because 3 is not an even number.
(10 XOR 8) = 2, so M = 8 is possible as it is the largest possible value of M satisfying the necessary conditions.
Input: N = 5
Output: 3
(5 XOR 4) = 1, so M = 4 is not possible because 1 is not an even number.
(5 XOR 3) = 6, so M = 3 is possible as 6 is an even number and 3 is the largest possible value of M (which is less than N).
方法:
在解决问题时需要进行以下观察:
- 以二进制形式表示的奇数的最低有效位 (LSB) 为 1,而以二进制形式表示的偶数的最低有效位 (LSB) 为 0。
- 在进行异或运算时,如果设置的位数为奇数,则 XOR 值为 1。如果设置的位数为偶数,则 XOR 值为 0。
- 因此,我们需要对两个奇数或两个偶数进行异或,以获得一个偶数作为结果。
由上面的解释,可以通过以下步骤解决问题:
- 如果 N 是奇数,则小于 N 的最大奇数将是N – 2 。
- 如果 N 是偶数,则小于 N 的最大偶数将是N – 2 。
- 因此,如果 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)