I’ve been doing some little code quizes just to catch back up on my coding after graduating but this one got my stump. Here’s the question:
Given a number n and two integers p1,p2 determine if the bits in position p1 and p2 are the same or not. Positions p1,p2 and 1 based.
Example
22,3,2 would be true because it’s 0001 0110 because the 2 and 3 position are the same.
I solved it one way which is to convert the decimal to binary and then into to a string and check if the bits in the positions are the same, but I feel there’s an easier way to do with bit manipulation but i’m not really good with it. I was thinking if I could just shift the bits to the first position and compare them I could get the answer but then I ran into the problem when I shift them to the shift left since they just overflow.
You could shift the interesting bits to the least significant position and then mask off all the other bits with
&.Assuming
p1andp2are zero-based indexes counting from the least significant bit: