-
[LeetCode] 461. Hamming DistanceLeetCode 2021. 11. 19. 12:48728x90
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
Hamming Distance - Easy

x와 y가 주어졌을때, Hamming distance를 구하는 문제다.
Hamming distance란, 서로다른 비트의 수를 의미한다.
서로 다른 비트가 만났을 때, 1을 내뱉게 되는 XOR 연산자를 사용하면 편하다.
x XOR y 연산을 실행하고, 1의 자리 비트를 더하고 오른쪽으로 시프트를 해주면 된다.
전체 풀이 코드
class Solution { public: int hammingDistance(int x, int y) { int ret = 0, z = x^y; while (z) { if (z&1) ret++; z=z>>1; } return ret; } };'LeetCode' 카테고리의 다른 글
[LeetCode] 952. Largest Component Size by Common Factor (0) 2021.11.23 [LeetCode] 540. Single Element in a Sorted Array (0) 2021.11.20 [LeetCode] 448. Find All Numbers Disappeared in an Array (0) 2021.11.18 [LeetCode] 498. Diagonal Traverse (0) 2021.11.17 [LeetCode] 62. Unique Paths (0) 2021.11.17