java - 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 -
i've been doing little code quizes catch on coding after graduating 1 got stump. here's question:
given number n , 2 integers p1,p2 determine if bits in position p1 , p2 same or not. positions p1,p2 , 1 based.
example
22,3,2 true because it's 0001 0110 because 2 , 3 position same.
i solved 1 way convert decimal binary , string , check if bits in positions same, feel there's easier way bit manipulation i'm not it. thinking if shift bits first position , compare them answer ran problem when shift them shift left since overflow.
you shift interesting bits least significant position , mask off other bits &
.
assuming p1
, p2
zero-based indexes counting least significant bit:
bool same_bits = (((n >> p1) & 1) == ((n >> p2) & 1))
Comments
Post a Comment