位1的个数
将原始数据右移
public int hammingWeight(int n){
int count = 0;
for (int i = 0;i < 32;i++){
count += (n>>i)&1;
}
return count;
}
每次删除最后一位1
public int hammingWeight(int n){
int count = 0;
while (n != 0){
n=n&(n-1);
count++;
}
return count;
}
比特位计算
public static int[] countBits(int num) {
int[] bits = new int[num + 1];
for (int i = 0; i <= num; i++) {
for (int j = 0; j < 32; j++) {
bits[i] += (i >> j) & 1;
}
}
return bits;
}
颠倒无符号整数
public static int reverseBits(int n) {
int reversed = 0, power = 31;
while (n != 0) {
reversed += (n & 1) << power;
n >>>= 1;
power--;
}
return reversed;
}
位运算实现加法
public int getsum(int a,int b){
while (b != 0){
int sign = (a & b)<<1;
a = a^b;
b = sign;
}
return a;
}
递归乘法
public int multiply(int A,int B){
int min = Math.min(A,B);
int max = Math.max(A,B);
int ans =0;
for (int i =0;min !=0;i++){
//位为1时才更新ans,否则max一直更新
if((min&1)==1){
ans += max;
}
min >>=1;
max +=max;
}
return ans;
}