DEV Community

Cesar Del rio
Cesar Del rio

Posted on • Updated on

#2 - Hamming Distance CodeWars Kata (6 kyu)

#2 - Hamming Distance (6 kyu)


The hamming distance between a pair of numbers is the number of binary bits that differ in their binary notation.

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] 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) ){

  return acc
Enter fullscreen mode Exit fullscreen mode

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.

My Github
My twitter
Solve this Kata

Discussion (0)