检查偶数或奇数`1`位在若干 [英] Checking even or odd `1` bits in a number
问题描述
我要检查是否有数量全部偶数或奇数位设置且仅他们。对于例如:
I want to check if number has all even or odd bits set to one and only them. For eg.:
数 42
是正确的,因为在二进制code 101010
它拥有一切,只有偶数位套 1
。
数 21
也是正确的, 10101
。
Number 42
is correct, because in a binary code 101010
it has all and only even bits sets to 1
.
Number 21
is also correct, 10101
.
数 69
为如。 1000101
是不正确的,因为只有三奇位集来 1
。
Number 69
for eg. 1000101
is not correct, because there are only three odd bits sets to 1
.
我已经用不同的操作与试过^&安培;,>&GT中,<<
,我仍然不知道我怎么可以这样用这些运营商。是的,我需要在 C
。
I've tried using different operations with ^, &, >>, <<
and i still have no idea how can i do this using these operators. Yes, i need to do this using logical operators in C
.
推荐答案
这些数字有该属性(X ^(X GT;&GT; 1))+ 1
是2的功率和是
是2的幂,如果 Y'放大器; (Y - 1)== 0
Those numbers have that property that (x ^ (x >> 1)) + 1
is a power of 2. And y
is a power of 2 if y & (y - 1) == 0
所以,一个测试可能是((X ^(X GT;&GT; 1))+ 1)及(X ^(X GT;&GT; 1))== 0
这将适用于任何规模的数
So one test could be ((x ^ (x >> 1)) + 1) & (x ^ (x >> 1)) == 0
which would work for numbers of any size.
这篇关于检查偶数或奇数`1`位在若干的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!