I'm writing a Sudoku solver and I have to calculate the what I learned was called the hamming distance of an int
to 0
, e.g. the hamming distance of 7
(111
in binary) to 0
is 3
. So I simply do:
for(int dist = 0 ; num != 0 ; num>>=1) dist += (num&1);
Although that works fine, I find it a bit clumsy. I tried to come up with a binary operation trick to calculate the distance (mostly for fun), but I could only find a way that works for a distance of 1
:
(num-1) ^ ((num<<1)-1) == num → true only if hamming dist to 0 == 1
I looked on StackOverflow and on the Net, but I couldn't find anything.
Assuming that num
is never negative and always smaller than 512
, is there a nicer/more elegant way to evaluate it, perhaps some binary operations tricks? If not, given the assumptions above, is there an approximation of the hamming distance that would always be within an error < 1
?