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

Your email address will not be published. Required fields are marked *