我正在编写Sudoku求解器,我必须计算出我学到的称为int
to0
的汉明距离,例如to 7
(111
以二进制形式)的汉明距离为0
is 3
。所以我只是做:
for(int dist = 0 ; num != 0 ; num>>=1) dist += (num&1);
尽管效果很好,但我觉得它有点笨拙。我试图提出一个二进制运算技巧来计算距离(主要是为了好玩),但是我只能找到一种适用于距离为的方法1
:
(num-1) ^ ((num<<1)-1) == num → true only if hamming dist to 0 == 1
我查看了StackOverflow和网上的内容,但找不到任何东西。
假设num
是从来没有否定,总是小于512
,有没有对其进行评估,或许某些二元运算技巧一个更好/更优雅的方式?如果不是这样,则根据上述假设,海明距离是否始终在误差范围内< 1
?
在Java中,您可以使用静态方法Integer.bitCount(int i)
如果您需要另一种语言的帮助,那么这是java源代码,应该可以毫不费力地进行翻译。
/**
* Returns the number of one-bits in the two's complement binary
* representation of the specified {@code int} value. This function is
* sometimes referred to as the <i>population count</i>.
*
* @param i the value whose bits are to be counted
* @return the number of one-bits in the two's complement binary
* representation of the specified {@code int} value.
* @since 1.5
*/
public static int bitCount(int i) {
// HD, Figure 5-2
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句