使用 1 到 N 范围内的数字计算对中不同的 XOR 值
给定一个数字N 。任务是使用从1到N的数字来计算任何可能对的不同 XOR 的数量。
例子:
Input: N = 3
Output: 4
Explanation: Following are the all possible pairs using elements from 1 to N inclusive.
1^1 = 0
1^2 = 3
1^3 = 2
2^2 = 0
2^3 = 1
3^3 = 0
Therefore, there are 4 distinct possible XOR values.
Input: N = 2
Output: 2
方法:这个问题是基于观察的。请按照以下步骤解决给定的问题。
- 对于N = 1和N = 2 ,所需输出分别为1和2 。
- 现在对于N≥3 ,有两种可能的情况:
- 如果N不是 2 的幂,那么总共会有't'个数字,其中t是2的幂,紧邻数字N 。它们从[0 到 t – 1]不等。因为假设N = 5或6或7在上述所有情况下,值都从[0, 1, 2, 3, 4, 5, 6, 7]变化。
- 如果N是 2 的幂,那么除了数字本身之外,所有数字都是可能的。因为假设N = 4在二进制中它是“100” ,所以我们知道如果两个位不同,XOR 运算给出“ 1” ,否则给出0 。可能的值为[0, 1, 2, 3,
4, 5, 6, 7] 。
下面是上述方法的实现。
C++
// C++ code to implement above approach
#include
#include
using namespace std;
int findDistinctXOR(int n)
{
// Corner case
if (n == 1) {
cout << 1 << endl;
}
if (n == 2) {
cout << 2 << endl;
}
long long x, next;
x = log2(n);
// if n is power of two
if ((n & (n - 1)) == 0) {
next = pow(2, x + 1);
cout << next - 1 << endl;
}
else {
next = pow(2, x + 1);
cout << next << endl;
}
}
// Driver Code
int main()
{
int N = 3;
findDistinctXOR(N);
return 0;
}
Java
// Java code to implement above approach
//include
import java.util.*;
class GFG
{
static void findDistinctXOR(int n)
{
// Corner case
if (n == 1) {
System.out.print(1 +"\n");
}
if (n == 2) {
System.out.print(2 +"\n");
}
long x, next;
x = (long) Math.log(n);
// if n is power of two
if ((n & (n - 1)) == 0) {
next = (long) Math.pow(2, x + 1);
System.out.print(next - 1 +"\n");
}
else {
next = (long) Math.pow(2, x + 1);
System.out.print(next +"\n");
}
}
// Driver Code
public static void main(String[] args)
{
int N = 3;
findDistinctXOR(N);
}
}
// This code is contributed by 29AjayKumar
Python3
# Python code for the above approach
import math as Math
def findDistinctXOR(n):
# Corner case
if (n == 1):
print(1)
if (n == 2):
print(2)
x = None
next = None
x = Math.floor(Math.log2(n))
# if n is power of two
if ((n & (n - 1)) == 0):
next = Math.pow(2, x + 1)
print((next - 1))
else:
next = Math.pow(2, x + 1)
print(int(next))
# Driver Code
N = 3
findDistinctXOR(N)
# This code is contributed by Saurabh Jaiswal
C#
// C# code to implement above approach
using System;
class GFG{
static void findDistinctXOR(int n)
{
// Corner case
if (n == 1)
{
Console.WriteLine(1);
}
if (n == 2)
{
Console.WriteLine(2);
}
long x, next;
x = (long)Math.Log(n, 2);
// If n is power of two
if ((n & (n - 1)) == 0)
{
next = (long)Math.Pow(2, x + 1);
Console.WriteLine(next - 1);
}
else
{
next = (long)Math.Pow(2, x + 1);
Console.WriteLine(next);
}
}
// Driver Code
public static void Main()
{
int N = 3;
findDistinctXOR(N);
}
}
// This code is contributed by ukasp
Javascript
输出
4
时间复杂度: O(1)
辅助空间: O(1)