[LeetCode] Hamming Distance using Bitwise

Khanh Vo
sharing and learning
2 min readAug 7, 2020

I think this topic is really fascinating and I wanna share some of my viewpoints about the solution to this topic

Let’s get started

First of all, using XOR bitwise

As you can see, the value “result” is referred to x ^ y, and we have the attributes of XOR table:

so we using XOR in this case to take the value which includes all different values of x and y

Example:
x = 1 , y = 4

so x ^ y = 0001 ^ 0100(we have 2 different values in this case) = 0101

=> So we can take the different values from x and y and combine into “result” value.
Move to next step, the while loop also with the purpose like Dynamic programming

in the while loop to update the result value we use the shift right bitwise,
we have 0101(5) and take a look to the If condition ((result & 1) == 1)

Take the above example to help you easy to understand

we using AND(&) bitwise with value 0001(1)
0101 & 0001 = 0001(1) so in this case 1 == 1 so count + 1,
we using shift right(>>) and continue with If condition, not the value compare is following below:

0010 & 0001 = 0000(0) so in this case 0 != 1 so count + 0
summary the condition inside the while loop we can understand like this:
1/ the If condition using (result & 1) to verify the last bit in result value is the 1 value or not, if the last bit is 1 we will plus 1 for the count value
2/ the Shift right (result >> = 1) will update the last bit value.

Conclusion, I think through this topic we can have a better understanding of bitwise in java (XOR, AND, SHIFT RIGHT) and the ways we can combine all of them together.

So that all for this topic. Hope that you can learn some new things from my sharing. Enjoy and Keep Learning!

--

--