## Given a number having only one ‘1’ and all other ’0’s in its binary representation, find position of the only set bit.

Last Asked at @Microsoft

Say number is : 5 so its binary is 0101 , so this number is not having only 1 and other 0

Lets Say number is 16 , so it binary is , 10000

So we can understand that if there is only 1 and rest all are 0 then the number should be perfect Square. ( this can be helpful in testing, or input test case).

ALGORTIHM :

1. Check if Number is power of two ( Else return ) 2. Set two variables 'i' for looping and 'pos' for position of set bit. 3. Run Loop, do boolean AND operation of 'i' and 'n' (input number). When result of this operation is one set the 'pos' variable.

OR

- We can Do right Shift Operation of number until we find 1.

CODE :

#include <stdio.h> int isPowerOfTwo(unsigned n) { return (! (n & (n-1)) ); } // Returns position of the only set bit in 'n' int findPosition(unsigned n){ if (!isPowerOfTwo(n)) return -1; unsigned count = 0; // One by one move the only set bit to right till it reaches end while (n){ n = n >> 1; // increment count of shifts ++count; } return count; } int main(void) { int n = 4; int pos = findPosition(n); (pos == -1)? printf("n = %d, Invalid number\n", n): printf("n = %d, Position %d \n", n, pos); n = 5; pos = findPosition(n); (pos == -1)? printf("n = %d, Invalid number\n", n): printf("n = %d, Position %d \n", n, pos); n = 128; pos = findPosition(n); (pos == -1)? printf("n = %d, Invalid number\n", n): printf("n = %d, Position %d \n", n, pos); return 0; }

Output:

n = 4, Position 3

n = 5, Invalid number

n = 128, Position 8