--- title: 'LeetCode 461. Hamming Distance' disqus: hackmd --- # LeetCode 461. Hamming Distance ## Description 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 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. Input: x = 3, y = 1 Output: 1 ## Constraints 0 <= x, y <= 2^31^ - 1 ## Answer Hamming Distance就是x要改變幾個位元才會變成y,ex:001 , 100 ,要改變最後一位變0然後第一位變1,總共兩位。此題可取兩者相異的位數,而取XOR時相異為1,所以只要取XOR算1的個數就知道要變幾個數。 ```Cin= int hammingDistance(int x, int y){ int count = 0,temp = x^y; while(temp){ count++; temp&=(temp-1); } return count; } ``` ## Link https://leetcode.com/problems/hamming-distance/ ###### tags: `Leetcode`