Harold Aptroot

Imagine you have an integer x, and you want to find the closest integer (unequal to x) that has the same hamming weight.

There is a relevant Q&A on SO, link at the bottom.

Here's an alternative with fewer operations than anything mentioned there: let y = -x & (x + 1) in x ^ y ^ (y >> 1)

How does that work? I don't really know, I pulled this out of the void with a SAT solver. Basically magic.

SO: (careful, the decent answers are buried deep) stackoverflow.com/q/38523733/5

Stack OverflowFind the closest integer with same weight O(1)I am solving this problem: The count of ones in binary representation of integer number is called the weight of that number. The following algorithm finds the closest integer with the same weight...