#2 - Hamming Distance CodeWars Kata (6 kyu)
Cesar Del rio
Posted on January 1, 2022
#2 - Hamming Distance (6 kyu)
Instructions:
Task
The hamming distance between a pair of numbers is the number of binary bits that differ in their binary notation.
Example
For a = 25, b= 87, the result should be 4
25: 00011001
87: 01010111
The hamming distance between these two would be 4 ( the 2nd, 5th, 6th, 7th bit ).
Input/Output
[input] integer a
First Number. 1 <= a <= 2^20
[input] integer b
Second Number. 1 <= b <= 2^20
[output] an integer
My solution:
function hammingDistance (a, b) {
const decToBin= (n)=>{
return("00000000000000000000"+(n >>> 0).toString(2)).slice(-20)
}
let aBin = decToBin(a)
let bBin = decToBin(b)
let acc = 0;
for(let i = 0; i<20 ; i++ ){
if(aBin.charAt(i) !== bBin.charAt(i) ){
acc++
}
}
return acc
}
Explanation
I started converting the decimal number to binary code, for this I used .toString(2) to convert it to binary, but because I had some issues with the number of digits in the result, I added 20 zeros and then I sliced it so I eliminated the extra zeros and I could get the result of a 20 digits binary number.
Then I started a loop with 20 iterations because it is a 20 digits binary number that will check every element of the string and if they aren't equal it will add 1 to the accumulator which contains the last result.
Posted on January 1, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.