[leetcode #461] Hamming Distance

Seongyeol Shin·2021년 11월 19일
0

leetcode

목록 보기
79/196
post-thumbnail

Problem

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, return the Hamming distance between them.

Example 1:

Input: x = 1, y = 4
Output: 2
Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑
The above arrows point to positions where the corresponding bits are different.

Example 2:

Input: x = 3, y = 1
Output: 1

Constraints:

0 <= x, y <= 2³¹ - 1

Idea

아주 쉬운 문제다. 두 수를 bit로 표현했을 때 서로 다른 bit의 개수가 몇 개인지 구하면 된다.

우선 xor 연산을 통해 서로 다른 bit만 1로 남긴다. 두 수의 범위가 int이므로 32개의 bit를 right shift해서 1과 AND 연산을 해 1이 나오면 hamming distance를 1씩 증가시킨다.

모든 bit를 비교해한 뒤 계산한 hamming distance를 리턴하면 된다.

Solution

class Solution {
    public int hammingDistance(int x, int y) {
        int xor = x ^ y;
        int res = 0;
        int mask = 1;

        for (int i=0; i < 32; i++) {
            if ((xor & mask) == 1) {
                res++;
            }
            xor = xor >> 1;
        }

        return res;
    }
}

Reference

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

profile
서버개발자 토모입니다

0개의 댓글