I recently saw an interview question asking the following:
Given a 32 bit number, write pseudo code to flip the second last bit
What is the best/easiest way to do this?
I recently saw an interview question asking the following:
Given a 32 bit number, write pseudo code to flip the second last bit
What is the best/easiest way to do this?
a = 0x80000000; // the second last bit set
if( i & a == 0) // not set in i -> set it
i |= a;
else // set -> un-set it in i
i &= ~a;
edit: arg, of course you can XOR it :-) But 2 is the second bit not the second last bit. Maybe better to talk about MSB and LSB.
X ^ (1<<n) will toggle the state of nth bit in the number X.
I see some answers interpret "last bit" as MSB, others as LSB. Perhaps they're looking for candidates smart enough to pause and ask for clarification before cranking out code. That's very important in real-world work.