英文:
What's an intuitive way to check if a number contains two consecutive 0s in it's binary representation?
问题
所以,如果我想要检查一个数字是否包含两个连续的1,我可以简单地执行 (n & (n >> 1)) == 0
。我在考虑,要检查数字是否包含两个连续的0,你可以做同样的事情,只是反转位:(~n & (~n >> 1)) == 0
。然而,这似乎并没有产生正确的结果。从逻辑上讲,反转位并应用相同的原理,以检查两个连续的1是否相邻,这是有道理的。是否有一种更高效和/或更直观的方法来做到这一点呢?
英文:
So, If I want to check that a number contains two consecutive 1s, I can simply do (n & (n >>> 1)) == 0
<br> I'm thinking that to check if the number contains two consecutive 0's you would do the same thing but just inverting the bits: (~n & (~n >>> 1)) == 0
. However, this doesn't seem to produce the correct result. It does make sense, logically, invert the bits and apply the same principle to check if two consecutive 1s are next to each other. Is there a more efficient and/ or intuitive way to do this?
答案1
得分: 2
当且仅当 n
在第一个1后没有连续的零时,下一个语句使得 n
比一个2的幂次少1:
n |= n >>> 1
当且仅当 n
比一个2的幂次少1时,下一个语句使得 n
等于零:
n &= n + 1
英文:
If and only if n
has no consecutive zeros after the first 1, the next statement makes n
one less than a power of 2:
n |= n >>> 1
If and only if n
is one less than a power of 2, the next statement makes n
equal to zero:
n &= n + 1
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论