【LeetCode】461. Hamming Distance
阿新 • • 發佈:2019-01-30
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
, calculate the Hamming distance.
題目:求漢明距離,即兩個數不同位數的數量
思路:本來是想每比較一位,同時再x,y右移一位,判斷依據為異或後是否為1.
方法第一遍沒通過,再看到異或後,又想到先將兩個數異或,再看二進位制中為1位的數量即可。
程式碼:
class Solution {
public int hammingDistance(int x, int y) {
int ret = 0;
int z = x ^ y;
while(z!=0){
if((z&1)==1)
ret++;
z>>=1;
}
return ret;
}
}