191. 位1的个数
位操作
class Solution {
public int hammingWeight(int n) {
int sum = 0;
while (n != 0) {
sum++;
n &= (n - 1);
}
return sum;
}
}
平行算法求位1的个数
先从两位二进制开始计算,逐步计算出结果
两个相邻的二进制为00,则为00,即0个,
两个相邻的二进制为01或10,则为01,即1个,
两个相邻的二进制为11,则为11,即2个。
把两位的结果归并到四位二进制中,四位到八位…
public class Solution {
public int hammingWeight(int n) {
int temp = n;
temp = (temp & 0x55555555) + ((temp>> 1) & 0x55555555); //temp相邻位相加
temp = (temp & 0x33333333) + ((temp>> 2) & 0x33333333); //temp相邻(以2为单位)相加
temp = (temp & 0x0f0f0f0f) + ((temp>> 4) & 0x0f0f0f0f); //temp相邻(以4为单位)相加
temp = (temp & 0x00ff00ff) + ((temp>> 8) & 0x00ff00ff); //temp相邻(以8为单位)相加
temp = (temp & 0x0000ffff) + ((temp>>16) & 0x0000ffff); //temp相邻(以16为单位)相加
return temp;
}
}
338. 比特位计数
动态规划 + 最高有效位
把最高位的 1 当孤儿看,只是当做 工具数
class Solution {
public int[] countBits(int num) {
int[] res = new int[num+1];
int i = 0, b = 1;
while(b <= num) {
while(i < b && i+b <= num) {
res[b + i] = res[i] + 1;
i++;
}
i = 0;
b <<= 1;
}
return res;
}
}
动态规划 + 最低有效位
同上
class Solution {
public int[] countBits(int num) {
int[] res = new int[num+1];
for(int i = 1; i < num; i++)
res[i] = res[i >> 1] + (i & 1);
return res;
}
}
动态规划 + 最后设置位
res[i & (i - 1)] 会找到当前最后数最后的1,然后找到比当前数少一个 1的数
11001000:(11 001 000 & 11 000 111) = 11 000 000
class Solution {
public int[] countBits(int num) {
int[] res = new int[num+1];
for(int i = 1; i <= num; i++)
res[i] = res[i & (i-1)] + 1; return res;
}
}
190. 颠倒二进制位
移位操作
从前往后遍历,一位一位的移到后面赋给res
public class Solution {
public int reverseBits(int n) {
int res =0;
for (int i = 0; i <= 31; i++) {
res += (n >> i & 1) << (31 - i);
}
return res;
}
}
平行算法
public class Solution {
public int reverseBits(int n) {
n = ((n & 0xffff0000) >>>16) | ((n & 0x0000ffff) <<16);
// n = (n >>> 16) | (n << 16); // 可以这么简写
n = ((n & 0xff00ff00) >>> 8) | ((n & 0x00ff00ff) << 8);
n = ((n & 0xf0f0f0f0) >>> 4) | ((n & 0x0f0f0f0f) << 4);
n = ((n & 0xcccccccc) >>> 2) | ((n & 0x33333333) << 2);
n = ((n & 0xaaaaaaaa) >>> 1) | ((n & 0x55555555) << 1);
return n;
}
}
来源:力扣(LeetCode)
链接:
https://leetcode-cn.com/problems/number-of-1-bits/solution/wei-1de-ge-shu-by-leetcode/
https://leetcode-cn.com/problems/counting-bits/solution/bi-te-wei-ji-shu-by-leetcode/