What's an intuitive way to check if a number contains two consecutive 0s in it's binary representation?

huangapple go评论73阅读模式
英文:

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 &amp; (n &gt;&gt;&gt; 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 &amp; (~n &gt;&gt;&gt; 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 &gt;&gt;&gt; 1

If and only if n is one less than a power of 2, the next statement makes n equal to zero:

n &amp;= n + 1

huangapple
  • 本文由 发表于 2020年9月30日 02:38:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/64125672.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定