There is an array of numbers, where each number occurs even number of times except for one number which occurs odd number of times. Find out the number.
Approach: When you XOR a number even number of times, it becomes zero. So XOR all the numbers in the array, the result will be the number which occurred odd times.C++ program to find the number occurring odd number of times
#include <iostream> using namespace std; const int MAX_INPUT = 7; int main() { int input[MAX_INPUT] = { 123, 456, 123, 678, 985, 985, 678 }; int output = 0; for(int i=0;i<MAX_INPUT;i++) output ^= input[i]; cout << "Odd number out is: " << output << endl; return 0; }Output:-
Odd number out is: 456
0 comments:
Post a Comment