Home | Projects | Notes > Problem Solving > EPI - 5.4. Find a Closest Integer with the Same Weight (bit manipulation)

EPI - 5.4. Find a Closest Integer with the Same Weight (bit manipulation)

 

Solutions in C

Solution 1

This solution uses bit swapping technique using shift and xor operation.

The key is to finding the algorithm: Swap the two rightmost consecutive bits that differ.

It is assumed that x is not 0, or all 1s.

Complexity Analysis:

Solution: