如何通过使用 2 位或更多数字的 XOR 运算符来执行此操作C++问题



XOR 对于个位数输入工作正常,但在使用 2 位或更多数字时完全搞砸了。如何仍然使用 XOR 制作此程序?

这基本上是问题:

查找缺少的号码

您将获得一个 n-1 个整数的列表,这些整数的范围为 1 到 n。列表中没有重复项。列表中缺少其中一个整数。编写有效的代码来查找缺少的整数。

我的程序是:

#include<iostream>
using namespace std;
int main(void)
{
int n; //number of elements
cout << "Enter the number of elements : ";
cin >> n;
//Declaring array
int arr[n-1];
//Taking input
for(int i = 0; i<n-1; i++)
cin >> arr[i];
//printing array
cout << "nElements are :";
for(int i = 0; i<n-1; i++)
cout << " " << arr[i];
//Declaring elements to take XOR
int x1 = arr[0]; // first element of array
int x2 = 1; //first element in natural number series i.e 1,2,3,4...
//taking XOR of all elements of the given array
for(int i = 1; i<n-1; i++)
x1 ^= arr[i];
//taking XOR of all the natural numbers till 'n'
for(int i = 2; i<arr[n-1]; i++)
x2 ^= i;
//Finally printing the output by taking XOR of x1 and x2
//because same numbers will be removed since (A^A) = 0 also (A^0) = A
cout << "nMissing number : " << (x1^x2) << endl;
return 0;
}

上述程序不适用于以下输入:

10
1 2 3 4 5 6 7 8 10

你的循环是错误的,你可以更改为:

//Declaring elements to take XOR
int x1 = 0; // for element of array
int x2 = 0; // for natural number series i.e 1,2,3,4...
//taking XOR of all elements of the given array
for (int i = 0; i < n-1; i++)
x1 ^= arr[i];
//taking XOR of all the natural numbers till 'n'
for (int i = 1; i != n + 1; i++)
x2 ^= i;

请注意,自然数范围大于 arr 大小。

最新更新