Jarvis and Lone Integer

Today Tony Stark is upset with Jarvis, as it blew the whole plan of him defeating the Flash in a parallel universe by showing him two images of Flash. Tony couldn't identify the real one and ended up getting hit hard. Jarvis is upset too and he wants to prove that it was not his mistake. Help Jarvis to prove himself faithful and true AI.

To prove, that Jarvis is not at fault, he is given N non-negative integers and he has to identify alone integer among them. A lone integer is defined as an integer in the given array of integers that is left alone after pairing each of the other integers. Two integers can be paired if they have the same value in the decimal number system and have different indices in the array. (Look at example case for better understanding and it is guaranteed that there is at most one such integer.)

Example:

Input:  n = 7, a = {8, 7, 8, 1, 6, 6, 7}
Output: 1

Approach

C++

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

long long loneInteger(long long nlong long a[])
{
    long long ans = a[0];
    for (long long i = 1i < ni++)
    {
        ans = ans ^ a[i];
    }
    if (ans == 0)
        return -1;
    else
        return ans;
}
int main()
{

    long long n = 7;
    long long a[n] = {8781667};

    cout << loneInteger(na<< "\n";

    return 0;
}


No comments:

Post a Comment