/**
* num binary cnt
* 0 0 0
* 1 1 1
* ---------------------------------
* 2 10 1+0
* 3 11 1+1
* ---------------------------------
* 4 100 1+0
* 5 101 1+1
* 6 110 1+0+1
* 7 111 1+1+1
* ---------------------------------
* 8 1000 1+0
* ...
* there's a fomular cnt[num] = cnt[num/2] + num%2
*/
public class Solution {
public int[] countBits(int num) {
int[] cnt = new int[num+1];
if (num == 0) return cnt;
cnt[1] = 1;
int k = 1;
while (true) {
// Math.pow returns double
int i = (int)Math.pow(2, k);
for (int j=i; j<=2*i-1; j++) {
if (j > num) return cnt;
cnt[j] = cnt[j-i]+1;
}
k++;
}
}
}
Leetcode 338. Counting Bits
最新推荐文章于 2023-12-19 12:04:55 发布