?LeetCode刷題實(shí)戰(zhàn)461:漢明距離
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, return the Hamming distance between them.
示例? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
示例 1:
輸入:x = 1, y = 4
輸出:2
解釋:
1 (0 0 0 1)
4 (0 1 0 0)
??↑? ↑
上面的箭頭指出了對(duì)應(yīng)二進(jìn)制位不同的位置。
示例 2:
輸入:x = 3, y = 1
輸出:1
解題
class?Solution?{
public:
????int?hammingDistance(int?x, int?y)?{
????????int?count=0;
????????while(x||y)
????????{
????????????if(x%2!=y%2) ++count;
????????????x/=2;
????????????y/=2;
????????}
????????return?count;
????}
};
LeetCode1-440題匯總,希望對(duì)你有點(diǎn)幫助!
評(píng)論
圖片
表情
