Update hamming-distance.md
This commit is contained in:
@ -1,10 +1,9 @@
|
|||||||
### Hamming distance between two numbers
|
### Hamming distance between two numbers
|
||||||
|
|
||||||
Use XOR operator.
|
Use XOR operator (`^`) to find the bit difference between the two numbers, convert to binary string using `toString(2)`.
|
||||||
Find the binary bit difference between two number using `^` operator.Convert the result to binary string using `toString(2)`.Get the difference by getting the number of 1's in the binary digit using `match(/1/g)`.
|
Count and return the number of `1`s in the string, using `match(/1/g)`.
|
||||||
```js
|
```js
|
||||||
const hammingDistance = (num1, num2) => {
|
const hammingDistance = (num1, num2) =>
|
||||||
return ((num1^num2).toString(2).match(/1/g) || '').length;
|
((num1^num2).toString(2).match(/1/g) || '').length;
|
||||||
}
|
|
||||||
//hammingDistance(2,3) -> 1
|
//hammingDistance(2,3) -> 1
|
||||||
```
|
```
|
||||||
|
|||||||
Reference in New Issue
Block a user