【leetcode】461. Hamming Distance
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.
Example 1:
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.
1、利用mask 统计每一位上的数字是否为1
1 class Solution { 2 public: 3 int hammingDistance(int x, int y) { 4 // xoring 之后统计每一位的一的个数 5 int res=0; 6 // int 型的数据 4个字节 最多32位的数据 7 int z=x^y; 8 for(int i=31;i>=0;--i){ 9 int mask=(1<<i); 10 if(z&mask){ 11 res++; 12 } 13 } 14 return res; 15 16 } 17 };
2、利用bulitn function (内建函数)直接统计每一位上1的个数
class Solution { public: int hammingDistance(int x, int y) { int z=x^y; return __builtin_popcount(z); } };