250x250
반응형
Notice
Recent Posts
Recent Comments
Link
N
(Leet Code JS)Hamming Distance 본문
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
반응형
'Leet Code 알고리즘' 카테고리의 다른 글
(Leet Code JS)Delete Operation for Two Strings (0) | 2022.06.23 |
---|---|
(Leet Code JS)Maximum Erasure Value (0) | 2022.06.18 |
(Leet Code JS)Repeated Substring Pattern (0) | 2022.05.13 |
(Leet Code JS)Find All Numbers Disappeared in an Array (0) | 2022.05.13 |
(Leet Code JS)Arranging Coins (0) | 2022.05.13 |