In the end I just got 13/15 are correct but which ones are wrong and which ones are right that I don’t know but want to know about it. Also I have doubt in 4th and 6th question of it.
I am unable to get which of my answers are wrong
can you share the questions?
i don’t have questions
Which one line function can be used to get index of the least significant bit that is on (first 1 from right to left in binary representation of an integer) ?
log2( N ^ -N ) + 1
log2( N | -N ) + 1
log2( N & -N ) + 1
log2( N ~ -N ) + 1
bitmask count set bits 2
Total number of factors of n
Total number of divisors of n
Total number of unset bits in binary representation of a n
Total number of set bits in binary representation of a n
Explanation
One can use the property of 2s-complement here.
Fastest way to find 2s-complement of a number is to get the rightmost set bit and flip everything to the left of it.
eg: consider a 4 bit system
4=0100
2s complement of 4 = 1100, which nothing but -4
4&(-4)=0100.
Notice that there is only one set bit and its at rightmost set bit of 4
Similarly we can generalise this for n.
n&(-n) will contain only one set bit which is actually at the rightmost set bit position of n.
since there is only one set bit in n&(-n) , it is a power of 2.
So finally we can get the bit position by:
log2(n&(-n))+1
where is question???
Why +1 in the end and log2 in the starting?
because without +1 we get index based on “zero based indexing”
but if we consider 1th bit not 0th bit then we have to add 1
bool get (int n)
{
int x = 0;
while( n )
{
x += n&1;
n = n>>1;
}
return x;
}
Above function will return :-
Total number of divisors of n
Total number of factors of n
Total number of unset bits in binary representation of a n
Total number of set bits in binary representation of a n
This was 5th question and according to me the ans of this is option d. I have doubt in the question I posted above which is an extension of this one.
got your point. thanks!
this will be the answer
extract last bit and add it to x
now remove last bit
so at the end x will contain sum of all set bits
which is nothing but Total number of set bits in binary representation of a n
@sakshi_singhal kindly give your feedback
it hardly takes a min
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.
What about this? I have query in this question and not in the question you answered.
which question? you can still ask
don’t worry
Is it possible to discuss it over a call?
i hope your doubt is resolved
so kindly give feedback