/**
* 对于所有的数字,只有两类:
* 1. 奇数:二进制表示中,奇数一定比前面那个偶数多一个 1,因为多的就是最低位的 1。
* 2. 偶数:二进制表示中,偶数中 1 的个数一定和除以 2 之后的那个数一样多。
* 因为最低位是 0,除以 2 就是右移一位,也就是把那个 0 抹掉而已,所以 1 的个数是不变的。
*/
class Solution {
public int[] countBits(int num) {
int[] result = new int[num + 1];
result[0] = 0;
for (int i = 1; i <= num; i++) {
// 如果为奇数
if (i % 2 == 1) {
result[i] = result[i - 1] + 1;
}
// 如果为偶数
else {
result[i] = result[i / 2];
}
}
return result;
}
}
class Solution {
public int[] countBits(int num) {
int[] res = new int[num + 1];
for (int i = 0; i <= num; ++i) {
res[i] = Integer.bitCount(i);
}
return res;
}
}
// private int popcount(int x) {
// int count;
// for (count = 0; x != 0; ++count)
// x &= x - 1; //zeroing out the least significant nonzero bit
// return count;
// }
leetcode338. 比特位计数
最新推荐文章于 2023-07-31 01:43:50 发布