Wednesday, January 17, 2024

CSES :: Introductory Algorithms :: Missing Number

Problem : Please find the problem here.

Explanation : Apply XOR of all n-1 numbers with numbers between 1 to n.

Code : missing number = (1^2^....^n) ^ (a[0]^a[1]^...a[n-1])

#include <bits/stdc++.h>
#define ll long long
using namespace std;

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    int n, x;
    cin >> n;
    ll res = 0;
    for (int i = 0; i < n-1; i++) {
        cin >> x;
        res ^= x;
    }
    for (int i = 1; i <= n; i++) {
        res ^= i;
    }

    cout << res;
    return 0;
}

No comments:

Post a Comment