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