338. Counting Bits
为什么80%的码农都做不了架构师?>>>
想法:用一个掩码获取除最高位之外的剩下的几位 其中掩码分别是 0,2-1,4-1,8-1,16-1,…
当mask = 7,x = 9时,ans[x&mask]是后面几位中数字1的个数
class Solution {
public int[] countBits(int num) {
int[] ans = new int[num+1];
ans[0] = 0;
int mask = 0;
for(int x=1;x<=num;x++){
ans[x] = 1+ans[(x&mask)];
if((mask&x)==mask){
mask = (mask<<1)+1;
}
}
return ans;
}
}
转载于//my.oschina.net/reter/blog/3008921
还没有评论,来说两句吧...