N

(Leet Code JS)Hamming Distance 본문

Leet Code 알고리즘

(Leet Code JS)Hamming Distance

naeunchan 2022. 5. 13. 16:51
728x90
반응형

https://leetcode.com/problems/hamming-distance/

 

Hamming Distance - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

주어진 x와 y를 이진수로 바꿔서 각 자릿수를 비교했을 때 다른 비트의 수를 구하면 된다.

 

먼저 x를 이진수로 바꾼 값을 저장할 배열 xArr과

y를 이진수로 바꿔 저장할 배열 yArr을 선언한다.

그리고 리턴할 answer = 0.

 

divide라는 함수를 이용해 인자로 들어온 n을 이진수로 만들어 arr에 저장한다.

 

이진수로 만들었으면 두 배열의 길이를 makeSameLength라는 함수로 맞춰주도록 한다.

 

이후 xArr과 yArr의 인덱스를 순회하면서 다른 비트의 수를 구하면 된다.

/**
 * @param {number} x
 * @param {number} y
 * @return {number}
 */
var hammingDistance = function(x, y) {
    const xArr = [];
    const yArr = [];
    let answer = 0;
    
    const divide = (n, arr) => {
        while(n){
            arr.push(n % 2);
            n = Math.floor(n / 2);
        }
    }
    
    const makeSameLength = (a, b) => {
        for(let i = a.length; i < b.length; i++){
            a.push(0);
        }
    }
    
    divide(x, xArr);
    divide(y, yArr);
    
    if(xArr.length < yArr.length){
        makeSameLength(xArr, yArr);
    } else{
        makeSameLength(yArr, xArr);
    }
    
    for(let i = 0; i < xArr.length; i++){
        if(xArr[i] !== yArr[i]){
            answer++;
        }
    }
    
    return answer;
};
728x90
반응형