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.
C
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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!