给定一个范围[L,R],任务是查找范围L到R(包括两个端点)中所有自然数的XOR值是偶数还是奇数。如果范围内所有数字的异或为偶数,则打印“偶数”,否则为奇数。
例子:
Input: L = 1, R= 10
Output: Odd
Input: L= 5, R=15
Output: Even
一个简单的解决方案是计算范围为[L,R]的所有数字的XOR,然后检查所得的XOR值是偶数还是奇数。
这种方法的时间复杂度将为O(n)。
一个有效的解决方案基于以下事实:
odd ^ odd = even
odd ^ even = odd
even ^ odd = odd
even ^ even = even
所有偶数的XOR将是偶数(与范围大小无关),并且如果奇数的计数是奇数,则最终XOR将是奇数,如果偶数则最终XOR将是偶数。
现在可以得出结论,
- If the count of Odd Numbers is even,
XOR of all odd numbers = Even
XOR of all even numbers = Even
Final XOR = Even ^ Even = Even - If the count of Odd Numbers is Odd,
XOR of all odd numbers = Odd
XOR of all even numbers = Even
Final XOR = Odd ^ Even = Odd
因此,我们要做的就是计算L到R范围内的奇数。
方法 :
- 计算[L,R]范围内的奇数。
- 检查奇数计数是偶数还是奇数。
- 如果计数为偶数则打印“偶数”,否则为“奇数”。
下面是上述方法的实现:
C++
// C++ program to check if XOR of
// all numbers in range [L, R]
// is Even or odd
#include
using namespace std;
// Function to check if XOR of all numbers
// in range [L, R] is Even or Odd
string isEvenOrOdd(int L, int R)
{
// Count odd Numbers in range [L, R]
int oddCount = (R - L) / 2;
if (R % 2 == 1 || L % 2 == 1)
oddCount++;
// Check if count of odd Numbers
// is even or odd
if (oddCount % 2 == 0)
return "Even";
else
return "Odd";
}
// Driver Code
int main()
{
int L = 5, R = 15;
cout << isEvenOrOdd(L, R);
return 0;
}
Java
// Java program to check if XOR of
// all numbers in range [L, R]
// is Even or odd
class GFG {
// Function to check if XOR of all numbers
// in range [L, R] is Even or Odd
static String isEvenOrOdd(int L, int R)
{
// Count odd Numbers in range [L, R]
int oddCount = (R - L) / 2;
if (R % 2 == 1 || L % 2 == 1)
oddCount++;
// Check if count of odd Numbers
// is even or odd
if (oddCount % 2 == 0)
return "Even";
else
return "Odd";
}
// Driver Code
public static void main(String[] args)
{
int L = 5, R = 15;
System.out.println(isEvenOrOdd(L, R));
}
}
C#
// C# program to check if XOR of
// all numbers in range [L, R]
// is Even or odd
using System;
class GFG {
// Function to check if XOR of all numbers
// in range [L, R] is Even or Odd
static string isEvenOrOdd(int L, int R)
{
// Count odd Numbers in range [L, R]
int oddCount = (R - L) / 2;
if (R % 2 == 1 || L % 2 == 1)
oddCount++;
// Check if count of odd Numbers
// is even or odd
if (oddCount % 2 == 0)
return "Even";
else
return "Odd";
}
// Driver Code
public static void Main()
{
int L = 5, R = 15;
Console.WriteLine(isEvenOrOdd(L, R));
}
}
Python3
# Python3 program to check if XOR of
# all numbers in range [L, R]
# is Even or odd
# Function to check if XOR of all numbers
# in range [L, R] is Even or Odd
def isEvenOrOdd( L, R ):
# Count odd Numbers in range [L, R]
oddCount = (R - L )/2
if( R % 2 == 1 or L % 2 == 1):
oddCount = oddCount + 1
# Check if count of odd Numbers
# is even or odd
if(oddCount % 2 == 0 ):
return "Even"
else :
return "Odd"
# Driver Code
L = 5
R = 15
print(isEvenOrOdd(L, R));
PHP
Javascript
输出:
Even
时间复杂度:O(1)
辅助空间:O(1)