Friday, January 17, 2014

Find Position of the only Set Bit

Problem: You are given a number having only one “1″ its binary representation,. You have to find position of it?
Solution:
First of all we will check if number is power of two, Beacuse then only its binary represenattion will contain only one “1″.
After that, start from rightmost bit and one by one check value of every bit. Following are steps:
1) Initialize two variables; i = 1 (for looping) and pos = 1 (to find position of set bit)
2) Inside loop, do bitwise AND of i and number ‘N’. If value of this operation is true, then “pos” bit is set, so break the loop and return position. Otherwise, increment “pos” by 1 and left shift i by 1 and repeat the procedure.

Rest, you can find here.

Reactions:

0 comments:

Post a Comment