给定正整数N ,任务是找到最大整数M ,以使0 <= M
例子:
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).
方法:
解决问题时需要进行以下观察:
- 以二进制形式表示的奇数以1作为其最低有效位(LSB),而以二进制形式表示的偶数以0作为其最低有效位(LSB)。
- 在执行XOR操作时,如果设置的位数为奇数,则XOR值为1。如果设置的位数为偶数,则XOR值为0。
- 因此,我们需要对两个奇数或两个偶数执行XOR运算,以得到一个偶数。
根据以上说明,可以通过以下步骤解决问题:
- 如果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)
如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。