반응형
https://leetcode.com/problems/hamming-distance/description/
Hamming Distance - LeetCode
Can you solve this real interview question? Hamming Distance - The Hamming distance [https://en.wikipedia.org/wiki/Hamming_distance] between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y,
leetcode.com
bitmasking으로 푼 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
1. 서로 다른 bit의 개수를 세줄 count를 선언한 후 0으로 초기화해줍니다.2. bit가 서로 다른 경우에만 1인 ^(XOR) 연산을 해 diff에 저장합니다.
📔 풀이과정
diff & 1연산으로 현재 bit가 1인지 확인해줍니다. 그 결과를 count에 더해줍니다. 그리고 diff의 bit를 오른쪽으로 옮겨 확인하는 것을 반복해줍니다.
📔 정답 출력 | 반환
count를 반환합니다.
📕 Code
📔 C++
class Solution {
public:
int hammingDistance(int x, int y) {
int count = 0;
int diff = x ^ y;
while(diff) {
count += diff & 1;
diff >>= 1;
}
return count;
}
};
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Implementation' 카테고리의 다른 글
(C++) - LeetCode (easy) 492. Construct the Rectangle (0) | 2023.03.29 |
---|---|
(C++) - LeetCode (easy) 485. Max Consecutive Ones (0) | 2023.03.28 |
(C++) - LeetCode (easy) 441. Arranging Coins (0) | 2023.03.15 |
(Python) - LeetCode (easy) 415. Add Strings (0) | 2023.03.13 |
(C++) - LeetCode (easy) 409. Longest Palindrome (0) | 2023.03.09 |