Developer/LEETCODE

461. Hamming Distance

cepiloth 2021. 9. 2. 18:42
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

난이도 : easy

문제

두 정수를 입력 받아 몇 비트가 다른지 계산하라

 

XOR 연산을 이용하여서 다른 비트를 구하도록 풀이한다.

Example 2 를 예를 들면

XOR 진리표

3 (0 1 1)
1 (0 0 1)

0 1 0 : 다른 비트는 하나만 있다.

 

코드

쉬프트 연산을 이용한 풀이

class Solution {
public:
    int hammingDistance(int x, int y) {
        
        unsigned long long cand = x ^ y;
        
        unsigned int dist = 0;
        while(cand) {
            if(cand & 1) {
                dist++;
            }
            cand = cand >> 1;
        }
        
        return dist;
    }
};

 

연산을 이용한 풀이

class Solution {
public:
    int hammingDistance(int x, int y) {
        int dist = 0, n = x ^ y;
        while (n) {
            ++dist;
            n &= n - 1;
        }
        return dist;
    }
};
728x90
반응형