Codewars 6 Kyu : IQ Test

题目

Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given numbers finds one that is different in evenness, and return a position of this number.

! Keep in mind that your task is to help Bob solve a real IQ test, which means indexes of the elements start from 1 (not 0)

Examples :

IQ.Test("2 4 7 8 10") => 3 // Third number is odd, while the rest of the numbers are even

IQ.Test("1 2 1 1") => 2 // Second number is even, while the rest of the numbers are odd

解题思路:

表面看我们似乎是需要从一串数据中找出与众不同的那一个,事实上根据抽屉原理,只有奇偶数两种情况,因此只需要判断奇偶的个数就可以找出哪一个是与众不同的数。

代码

using System;
using System.Linq;

public class IQ
    {
        public static int Test(string numbers)
        { 
             int[] arr=numbers.Split(' ').Select(int.Parse).ToArray();
             int num1=arr.Where(c=>c%2==0).Count();
             int num2=arr.Where(c=>c%2!=0).Count();
             if(num1==1){
             for(int i=0;i<=arr.Length;i++){if(arr[i]%2==0)return i+1;}
             }
             if(num2==1){
             for(int i=0;i<=arr.Length;i++){if(arr[i]%2!=0)return i+1;}
             }
             return 0;
        }
    }

发表评论

您的电子邮箱地址不会被公开。