Odd number out | Letuscode
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
Similarly in the array
{
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;
}
Read full article from Odd number out | Letuscode
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 is a simple implementation problem, which can be solved in one iteration.
When we are reading numbers, just keep track of the following information.
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.
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;
}
Read full article from Odd number out | Letuscode