Find the position of the set bit

I am trying to findout the position of the set bit ex: 4 the pos
of 0100 is 2 , in my code When I am dry run the code the code must be return the pos to 3 let suppose that In my code But it will return 1 ,
1.
4>0
no = 4, no = 2, so pos =1
2.
2>0
no =2, no = 1 , so pos =2
3.
1>0 then pos 3 finally but it return 1 I didn’t get this

@Vikaspal
Your question is unclear
Still from what I understood


@Aarnav-Jindal-1059677350830863
Cloud u please check my code what’s wrong in that. It helps to out to think in another way.

@Vikaspal
I didn’t understand your question before
Please reframe it then I can help you out

Sure I have to find the position of set bit in a Integer .Suppose we have like 4 in Binary 0100 so the pos of set bit is 2. I need to find this. What I Have done in code
pos=0;
while(no>0) {
no = no & 1;
no = no >> 1
pos++;
}
and return the pos that all,
Suppose if you take 1 as no the
1 > 0 and no = 1 & 1 which no = 1 and then no is right shift so it become zero and the pos is incremented by one, and it will simply return it.
But if take 4 as no then
4 > 0
no = 4 & 1 then no = 4 >> 1 then no = 2 and pos = 1
2 > 0 and so pos = 2
1 > 0 and so pos = 3
so pos finally it will 3 but in my code it will return only 1, I know that the set bit of 4 is 2 but actually the code even does not printing the wrong output ?
Hope u got me this time

@Vikaspal
Got it. Thanks.

Your approach fails : no = no & 1; here
when you do this no becomes 1 or 0 and then you divide it by two
Hence pos will always be 1

ya got it.
while((no& 1) != 1) {
pos++;
no = no >> 1
}
That wiil work for the number which can me expressed in 2^pow but what is we have number 7 so it will not find the pos of set bit as 111 ? what should we do?

@Vikaspal
Your current logic works for 7 as well
For 7 ans will be 0

@Aarnav-Jindal-1059677350830863
for 7 the binary is 111 so there is 3 set bit how it will works

@Vikaspal
When number is 7
Your loop wont start because no&1 will be equal to 1
So pos will remain 0

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

1 Like

@Aarnav-Jindal-1059677350830863 thanks

1 Like