C/C++ Program to Find the Number Occurring Odd Number of Times?


In this program we will see how we can get a number that is occurring odd number of times in an array. There are many different approaches. One of the easiest approach is performing ZOR operation. If a number is XORed with itself, it will be 0. So if a number XORed even number of times, it will be 0, otherwise the number itself.

This solution has one problem, if more than one element has odd number of occurrences, it will return one of them.

Algorithm

getNumOccurredOdd(arr, n)

begin
   res := 0
   for each element e from arr, do
      res := res XOR e
   done
   return res
end

Example

 Live Demo

#include <iostream>
using namespace std;
int getNumOccurredOdd(int arr[], int n) {
   int res = 0;
   for (int i = 0; i < n; i++)
      res = res ^ arr[i];
   return res;
}
int main() {
   int arr[] = {3, 4, 6, 5, 6, 3, 5, 4, 6, 3, 5, 5, 3};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout << getNumOccurredOdd(arr, n) << " is present odd number of times";
}

Output

6 is present odd number of times

Updated on: 30-Jul-2019

91 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements