Open In App

Algorithms | Bit Algorithms | Question 1

What is the return value of following function for arr[] = {9, 12, 2, 11, 2, 2, 10, 9, 12, 10, 9, 11, 2} and n is size of this array. 




int fun(int arr[], int n)
{
    int x = arr[0];
    for (int i = 1; i < n; i++)
        x = x ^ arr[i];
    return x;
}

(A)



0

(B)



9

(C)

12

(D)

2


Answer: (B)
Explanation:

Note that 9 is the only element with odd occurrences, all other elements have even occurrences. If the input array has all elements with even occurrences except one, then the function returns the only element with odd occurrences. Note that XORing an element with itself results in 0 and XOR of 0 with a number x is equal to x. Try following the complete program.

# include <iostream>
using namespace std;

int fun(int arr[], int n)
{
    int x = arr[0];
    for (int i = 1; i < n; i++)
        x = x ^ arr[i];
    return x;
}

int main()
{
  int arr[] = {9, 12, 2, 11, 10, 9, 12, 10, 9, 11, 2};
  int n = sizeof(arr)/sizeof(arr[0]);
  cout << fun(arr, n) << endl;
  return 0;
}

Hence option (B) is the correct answer.

Quiz of this Question
Please comment below if you find anything wrong in the above post

Article Tags :