位运算
191:位1的个数
public class Solution {
public int hammingWeight(int n) {
int count = 0;
while(n != 0){
if((n&1) == 1){
count++;
}
n = n >>> 1;
}
return count;
}
}
递归:
public class Solution {
public int hammingWeight(int n) {
return weight(n);
}
public int weight(int n){
if(n == 0) return 0;
int count = n&1;
return count + weight(n>>>1);
}
}
- 汉明距离
class Solution {
//1.根据x,y按位异或
public int hammingDistance(int x, int y) {
int count = 0;
while(x != 0 || y != 0){
if(((x & 1)^(y & 1))==1) count++;
x = x>>>1;
y = y>>>1;
}
return count;
}
}
class Solution {
//2.根据x先异或,再x计算1个数(191题)
public int hammingDistance(int x, int y) {
int count = 0;
x = x^y;
while(x != 0){
if(((x & 1)&1)==1) count++;
x = x>>>1;
}
return count;
}
}
- Total Hamming Distance