我最近看到一个面试问题,问如下:
给定一个 32 位数字,编写伪代码来翻转倒数第二位
最好/最简单的方法是什么?
#define 掩码 0x00000002
新 = 旧 ^ 面具
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.
X ^ (1<<n) will toggle the state of nth bit in the number X.
Exclusive Or with 2. For example i = i ^ 2
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;
编辑:arg,当然你可以 XOR 它:-) 但是 2 是第二位而不是倒数第二位。也许最好谈谈 MSB 和 LSB。
使用按位异或运算符?