采访:翻转比特
最近看到一个面试题,问了这样的问题:
给定一个32位数字,写伪 翻转倒数第二位的代码
最好/最简单的方法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
新=旧^面具
new = old ^ MASK
我看到一些答案将“最后一位”解释为 MSB,其他答案将“最后一位”解释为 LSB。也许他们正在寻找足够聪明的候选人,在编写代码之前停下来并要求澄清。这在现实工作中非常重要。
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.
与 2 异或。例如 i = i ^ 2
Exclusive Or with 2. For example i = i ^ 2
编辑:arg,当然你可以对其进行异或:-)但是 2 是第二位而不是倒数第二位。也许更好地讨论 MSB 和 LSB。
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.
使用按位异或运算符?
use a bitwise XOR operator?