Please explain the code..tried hard but not able to get the logic

find the first set bit

xor kyu karre hain number se…aur unset a bit ka kya matlab hai…please explain

@aarijrab, unset means making bit value to 0, so unset rightmost bit means making rightmost set bit to 0, (n & (n - 1)) unsets the rightmost bit , if you have doubt in this then do ask, and finally xor with n gives a number with only rightmost bit of n set ,we are doing xor here , because xor has the property of returning 0 when same bits are passed , and 1 when different bits are passed

i.e
for a^b=0;
when a=1 and b=1
or a=0 and b=0;
else a^b=1;
so if you have unset rightmost bit so only that bit will be set in the result and other bits will be unset as the bit value are same
this might be confusing at first so give it a try by taking some examples,
feel free to ask me in case of any doubt :slight_smile:

what is the need of unsetting a bit here…

we are unsetting the right most bit , because we can do it in one operation i.e. n&(n-1) , which will enable us to find the rightmost set bit,

could tell me where i am getting wrong in my code https://ide.codingblocks.com/s/342459

@aarijrab, when n&1==1, then return 0 , rightmost bit is at 0th position
corrected code :- https://ide.codingblocks.com/s/342462

thanks bro for helping

welcome bro !! please mark your doubt as resolved if no further doubt…

bhaiya one question…could you please tell me form where to prepare oops in c++…any book or channel…and best boo to learn c++ for placement …like book which covers all concepts of c++ in depth…and book from where i can prepare all mcq

https://www.learncpp.com/
this is a great site and is up to date, i prepared my oops from here
chapter : 8 ,9,10,11,12
more than enough content for interviews and online assesment

bhaiya sorry for disturbing…where can i prepare for mcq like debugging etc

yr i haven’t prepared for debugging, knowledge of language and somw experience is enough for debugging rounds.