Given an array of numbers which contains all even numbers except one, or all add numbers except one.
How do you find the different number?
For example consider the array [1, 2, 3, 5, 9], 2
is the different number.
Similarly in the array [10, 6, 7, 24, 36], 7
is the different number.
This problem was originally appeared on Codeforces.
This is a simple implementation problem, which can be solved in one iteration.
When we are reading numbers, just keep track of the following information.
- first even index
- first odd index
- even number count
At the end, check if the even number count is 1, If it is, then print first even index, otherwise print first odd index.
Here is the C++ code for this.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
int main() | |
{ | |
cin.sync_with_stdio(false); | |
int n; | |
cin >> n; | |
int first_even = 0, first_odd = 0; | |
int even_count = 0; | |
int ind = 1; | |
while( n-- ) | |
{ | |
int num; | |
cin >> num; | |
if( num & 1 ) | |
{ | |
if( first_odd == 0 ) | |
first_odd = ind; | |
} | |
else | |
{ | |
if( first_even == 0 ) | |
first_even = ind; | |
even_count++; | |
} | |
ind++; | |
} | |
if( even_count == 1 ) | |
cout << first_even << endl; | |
else | |
cout << first_odd << endl; | |
return 0; | |
} |