題目的要求是得出兩個整數(shù)的二進(jìn)制表示下對應(yīng)位數(shù)上的不同數(shù)字的位數(shù)。
下方是官網(wǎng)給出的范例,可以幫助理解。
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.
這個題目要解出來很簡單,只需要知道異或這個概念就行了:兩個數(shù)(二進(jìn)制)值相同得0,不相同得1。
因此只要設(shè)一個變量result = x ^ y
,再去數(shù)result表示為二進(jìn)制時1的個數(shù)就行了。代碼如下
public class Solution {
public int hammingDistance(int x, int y) {
String temp = Integer.toBinaryString(x ^ y);
int count = 0;
char[] tempArray = temp.toCharArray();
for (int i = 0; i < temp.length(); i++) {
if (tempArray[i] == '1') {
count += 1;
}
}
return count;
}
}
Top Solution里還提到了Java代碼庫里面已經(jīng)有內(nèi)置的函數(shù)Integer.bitCount(x)
來統(tǒng)計一個整數(shù)二進(jìn)制表示下1的個數(shù),所以此題還可以簡化成return Integer.bitCount( x ^ y);
。還一種不同的思路來計算一個數(shù)(二進(jìn)制表示時)1的個數(shù),通過每次右移再與1與依次檢驗每一位上是否為1
int result = x ^ y;
int count = 0;
for (int i = 0; i < 32; i++) {
count += (result >> i) & 1;
}
return count;