Working on Hamming Distance - need to add zeros to have two strings match length of longest string

197 views Asked by At

I'm trying to solve this hamming distance problem .. currently stuck with my while loop, which isn't adding '0's to meet the longest length (minLength) amongst the two strings. I'd like the shortestString to result to "001" but right now it's just doing "01" .. please help, thanks in advance.

var hammingDistance = function(x, y) {

var yString = y.toString(2); var xString = x.toString(2);

if(xString.length > yString.length){
    var minLength = xString.length;
    var shortestString = yString;
    var longestString = xString;
}
else{
    minLength = yString.length;
    shortestString = xString;
    longestString = yString;
}

while(shortestString.length < minLength){
    newString = '0' + shortestString;
    shortestString++;
    return newString;
}
console.log(newString);

}; hammingDistance(1, 4);

1

There are 1 answers

3
allnodcoms On BEST ANSWER

If you get rid of shortestString++; in your while loop it should work.

That variable is a string, so incrementing it could do all sorts of damage. You are essentially incrementing it anyway when you add the '0', and you are checking its length in the while condition.

You also need to move the return newstring outside of the while, at the moment your while loop will only ever execute once as the return breaks out of it in the first pass.