---
# System prepended metadata

title: \#461 Hamming Distance
tags: [leetcode, leetcode-easy]

---

# \#461 Hamming Distance
## *計算漢明距離:兩等長度字串(或任意型態)轉為二進位表示後, 相同位數不同值得數量*
## Log
 - build 20210901 by syhuang

## 初見2
 - XOR運算後搭配[#191](articles/Leetcode/easy/191.md)
 - leetcode submit runtime 38%, memory 64%
```javascript=
var hammingDistance = function(x, y) {
    return hammingWeight(x^y);
    
    function hammingWeight(n) {
        var result=0;
        while(n){
            if(parseInt(n&1)) result++;
            n>>>=1;
        }
        return result;
    };
};
```

## 初見
 - 逐個位元跑迴圈比較
 - leetcode submit runtime 8%, memory 92%
```javascript=
var hammingDistance = function(x, y) {
    let result = 0;
    let tx = x, ty = y;
    for(;tx>0 || ty>0; tx>>=1,ty>>=1){
        if((tx&1)!=(ty&1)) result++;
    }
    return result;
};
```
## 備註
- 初見即畢業
## 參考
###### tags: `leetcode`, `leetcode-easy`