Monday 20 February 2017

Problem and Technical Approach


a. An array has N number of positive integers. All numbers occur even number of times exception one number which occurs odd number of times. Find the number.

void GetOddNumberInArray(int[] items)
        {
            var result = 0;
            foreach (var item in items)
            {
                result = result ^ item; //XOR

            }
            Console.WriteLine("Odd number in the list is {0}", result);
        }
b.  Check if 2 numbers are equal or not without equal operator.
   
     if(a XOR b)==0 then a & b are equal or Not.
c. Number is multiple of 4 Or Not
  public static void ValidateMultipleof4(int n)
        {
            var result = 1;
            for(int i=2; i<=n;i++)
            {
                result = result ^ i;
            }
            if (result == n)
                Console.WriteLine("Multiple of 4");
            else Console.WriteLine("Not multiple of 4");

        OR  (n>>2) is equivalent of division by 4 && again n<<2 is multiplication by 4. So if doing this 2 bit shift operation twice produces same result will be good enough to validate it is multiple of 4.

d. two same array with one missing number. find out missing one
    Do the XOR starting with 0. missing will come out.
e. Odd Number validation, do the & with 1, if output is 0 number is even.

No comments:

Post a Comment