461. Hamming Distance

Leetcode Day 2

題目:
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.

Note:
0 ≤ x, y < 231.

Example:

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.

tips :
這道題的目的就是要求兩個(gè)數(shù)字之間的漢明距離。兩個(gè)數(shù)字之間的漢明距離是兩個(gè)數(shù)字二進(jìn)制下對(duì)應(yīng)位不同的個(gè)數(shù)。
思路:
將兩個(gè)數(shù)字的二進(jìn)制進(jìn)行異或運(yùn)算,不同的位數(shù)得到1,將1累加起來就是兩個(gè)數(shù)字的漢明距離。

⊕是XOR運(yùn)算:異或運(yùn)算就是如果兩個(gè)數(shù)字(0或者1)相同,則輸出為0; 如果兩個(gè)數(shù)字(0或者1)不相同,就輸出為a

  • a⊕0=a
  • a⊕a=0
  • a⊕b⊕a= (a⊕a)⊕b=b
  1. python

# 先將x,y表示為二進(jìn)制數(shù), 用函數(shù)bin
# 也可以通過對(duì)該數(shù)字除以2 i次,得到的余數(shù)即為第i 位(從右開始)
 def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        return bin(x^y).count('1')
 //
ans = 0
while x or y:
  ans += (x % 2) ^ (y % 2)
  x /= 2
  y /= 2
return ans
//
  1. C++
    將x和y異或操作之后計(jì)算n其中二進(jìn)制中1的個(gè)數(shù),其計(jì)算的方法是通過自身n和自身減一n-1的二進(jìn)制數(shù)逐位相與&,然后減一之后繼續(xù)循環(huán)直至為0,這樣也就將其二進(jìn)制中1的個(gè)數(shù)計(jì)算出來
class Solution{
public:
      int hammingDistance(int x, int y){
            int dist = 0, n =x^y;
            while(n){  // 
                ++dist;
                n &= n-1;
}

}


}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容