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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


(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 0 and XOR of 0 with a number x is equal to x.



Try following 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;
}


Quiz of this Question



My Personal Notes arrow_drop_up