Jun 132012
 

Given an Array of two elements one of which is 0, the other is either 0 or 1. You have to make both the elements of array 0.

But following are the constraints:

1.You can use only one operation, Complement (Logical NOT). No other mathematical operation is allowed.
2.You cannot use if-else or loop construct.
3.You cannot directly assign 0 to array positions

Solution:

There can be multiple ways to achieve this (all using logical NOT operator). Below are the four ways of doing it:

    arr[arr[1]] = arr[!arr[1]];
    arr[!arr[0]] = arr[!arr[1]];
    arr[arr[1]] = arr[arr[0]];
    arr[0] = arr[arr[0]]; arr[1] = arr[0];

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)