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; } |
chevron_right
filter_none
(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;
}
Recommended Posts:
- Algorithms | Analysis of Algorithms (Recurrences) | Question 11
- Algorithms | Analysis of Algorithms (Recurrences) | Question 9
- Algorithms | Analysis of Algorithms (Recurrences) | Question 11
- Algorithms | Analysis of Algorithms (Recurrences) | Question 1
- Algorithms | Analysis of Algorithms (Recurrences) | Question 3
- Algorithms | Analysis of Algorithms (Recurrences) | Question 6
- Algorithms | Analysis of Algorithms (Recurrences) | Question 11
- Algorithms | Analysis of Algorithms (Recurrences) | Question 4
- Algorithms | Analysis of Algorithms (Recurrences) | Question 2
- Algorithms | Analysis of Algorithms (Recurrences) | Question 8
- Algorithms | Analysis of Algorithms (Recurrences) | Question 7
- Algorithms | Analysis of Algorithms | Question 19
- Algorithms | Analysis of Algorithms | Question 10
- Algorithms | Analysis of Algorithms | Question 5
- Algorithms | Analysis of Algorithms | Question 11



