LeetCode - 461. Hamming Distance
題目意思:
這題主要是給予兩個Integer,再2進制表達下,有幾個bit不一樣(同位置)
解決方式:
先用XOR做運算,C++的語法為" ^ ",當兩個數字bit不相同,該bit做XOR後輸出為1,以Integer長度為中止條件,計算出現幾次1即為答案。
class Solution {
public:
int hammingDistance(int x, int y) {
int c = x^y;
int count = 0;
while(c>0)
{
if(c%2 == 1)
{
count++;
}
c/=2;
}
return count;
}
};
留言
張貼留言