본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 461. Hamming Distance

반응형

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;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.