461 漢明距離

兩個整數之間的漢明距離指的是這兩個數字對應二進制位不一樣的位置的數目。java

給出兩個整數 x 和 y,計算它們之間的漢明距離。網絡

注意:
0 ≤ x, y < 231.spa

示例:code

輸入: x = 1, y = 4leetcode

輸出: 2it

解釋:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑io

上面的箭頭指出了對應二進制位不一樣的位置。class

來源:力扣(LeetCode)
連接:https://leetcode-cn.com/problems/hamming-distance
著做權歸領釦網絡全部。商業轉載請聯繫官方受權,非商業轉載請註明出處。二進制

 

題解:方法

java Integer的位與運算方法:

class  Solution {
     public   int  hammingDistance( int  x,  int  y) {
         return  Integer.bitCount(x^y);
    }
}
 
 
 
題解2:
class  Solution {
     public   int  hammingDistance( int  x,  int  y) {
         int  cnt= 0 ;
         while (x!= 0 ||y!= 0 ){
             if ((y& 1 )!=(x& 1 ))
            cnt++;
            x>>= 1 ;
            y>>= 1 ;
        }
         return  cnt;
    }
}
相關文章
相關標籤/搜索