ctci/05. Bit manipulation/5.6. Conversion.md

33 lines
1.1 KiB
Markdown

# 5.6. Conversion
> Write a function to determine the number of bits you would need to flip to convert integer A to integer B
Input: 29 (or: 11101), 15 (or: 01111)
Output: 2
First need to convert to array of bits, right? Levenstein distance between them. Or just iterate the bits by doing num >> 1, get rightmost bit of both nums and do XOR. Sum up all numbers.
## Hints
> How would you figure out how many bits are different between two numbers?
Levenstein distance between the strings, but we're working with numbers. Iterate all bits and add up the differences.
> Think about what an XOR indicates. If you do a XOR b, where does the result have 1s? Where does it have Os?
XOR has result 0 if bits are different, 1 if bits are same.
## Solution
a ^ b makes XOR between a and b, then just iterate a c and increase count if the value at that point is 1. Then shift c to right, keep deleting the right most bit.
```c++
int bitSwapRequired(int a, int b) {
int count = 0;
for (int c = a ^ b; c != 0; c = c >> 1) {
count += c & 1;
}
return count;
}
```