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
, calculate the Hamming distance.
求x y的汉明距离,x和y按位异或得到的二进制,有多少个1就是结果。
C++(3ms):
1 class Solution { 2 public: 3 int hammingDistance(int x, int y) { 4 int t = x^y ; 5 int sum = 0 ; 6 while(t){ 7 t = (t-1)&t; 8 sum++ ; 9 } 10 return sum ; 11 } 12 };
C++(6ms):
1 class Solution { 2 public: 3 int hammingDistance(int x, int y) { 4 int t = x^y; 5 int num = 0 ; 6 while(t>0){ 7 if (t&1==1) 8 num++; 9 t>>=1; 10 } 11 return num ; 12 } 13 };
C++(3ms):
1 class Solution { 2 public: 3 int hammingDistance(int x, int y) { 4 int t = x^y; 5 int num = 0 ; 6 while(t>0){ 7 if (t%2==1) 8 num++ ; 9 t/=2; 10 } 11 return num; 12 } 13 };
C++(3ms):
1 class Solution { 2 public: 3 int hammingDistance(int x, int y) { 4 return __builtin_popcount(x^y); 5 } 6 };
java(11ms):
1 public class Solution { 2 public int hammingDistance(int x, int y) { 3 int t = x^y ; 4 return Integer.bitCount(t); 5 } 6 }