c++ - 如何通过对 2 位或更多位数字使用 XOR 运算符来解决此 C++ 问题

标签 c++ arrays search operators

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 大小。

关于c++ - 如何通过对 2 位或更多位数字使用 XOR 运算符来解决此 C++ 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52450443/

相关文章:

c++ - 设置动态数组的默认值

当我调用自己实现的搜索方法时,Java BST 程序崩溃

c++ - 通过在 2 个服务器之间相互发送套接字来共享套接字 (WINSOCK)

c++ - 如何将#define-constants 转移到另一个 C++ 项目?

c++ - 将指针传递给主函数后,无法正确打印内容

Python正则表达式查找字母数字字母指定的所有组合

Java 返回问题

c# - 即使 c++ dll/native 插件中有 exit(1),如何保留我的 unity3d 程序 (c# v3.5)?

c - 数组未正确填充

c - 如何从递归函数返回字符串数组?