From 991ad0368af004eb33a5db2b869d1e647e601904 Mon Sep 17 00:00:00 2001 From: anebz Date: Wed, 8 Apr 2020 15:04:52 +0200 Subject: [PATCH] 5.6. conversion --- 05. Bit manipulation/5.6. Conversion.md | 32 +++++++++++++++++++++++++ README.md | 1 + 2 files changed, 33 insertions(+) create mode 100644 05. Bit manipulation/5.6. Conversion.md diff --git a/05. Bit manipulation/5.6. Conversion.md b/05. Bit manipulation/5.6. Conversion.md new file mode 100644 index 0000000..8ba3a98 --- /dev/null +++ b/05. Bit manipulation/5.6. Conversion.md @@ -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; +} +``` diff --git a/README.md b/README.md index caad832..c923a30 100644 --- a/README.md +++ b/README.md @@ -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 * Flip bit to create longest sequence of 1s * (( n & (n-1)) == 0). n=? +* How many different bits do two numbers have. 11001 vs. 11010 = 2. Levenstein distance ## Chapter 7 Object-oriented design