5.6. conversion
This commit is contained in:
parent
2a262d36bf
commit
991ad0368a
|
|
@ -0,0 +1,32 @@
|
||||||
|
# 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;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
@ -55,6 +55,7 @@ If you can't afford to buy the book, you can find a free pdf [here](http://ahmed
|
||||||
* Binary to string
|
* Binary to string
|
||||||
* Flip bit to create longest sequence of 1s
|
* Flip bit to create longest sequence of 1s
|
||||||
* (( n & (n-1)) == 0). n=?
|
* (( n & (n-1)) == 0). n=?
|
||||||
|
* How many different bits do two numbers have. 11001 vs. 11010 = 2. Levenstein distance
|
||||||
|
|
||||||
## Chapter 7 Object-oriented design
|
## Chapter 7 Object-oriented design
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue