给一个整数 n
,对于 0 <= i <= n
中的每个 i
,计算其二进制表示中1的个数,返回一个长度为 n+1
的数组 ans
作为答案。
例如:
输入:n=2
输出:[ 0,1,1 ]
00-->0
01-->1
10-->1
输入:n=3
输出:[ 0,1,1,2]
00-->0
01-->1
10-->1
11-->2
分析:
m&(m-1)表示去掉二进制表示中最低位的一个1,则去掉几个1就表示原来有几个1,之后计算每个数字1的个数,存入数组
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* countBits(int n, int* returnSize){
int m=0;
int count=0;
int *ans=malloc(sizeof(int)*(n+1)); //开辟一块空间存储数组
for(int i=0;i<=n;i++){
m=i;
while(m){
m&=(m-1);
count++;
}
ans[i]=count;
count=0;
}
*returnSize=n+1;
return ans;
}