2023年7月27日 星期四

[338] Counting Bits

ㄜ.......
雖然是無痛PASS了,但是看不懂別人的 
while (temp)
{
    count++;
    temp= temp & (temp-1) ;
}
是怎麼辦到的  XD

/**
* Note: The returned array must be malloced, assume caller calls free().
*/

int count(int n)
{
int ret=0;
while (n>0)
{
ret += (n & 1);
n=n>>1;
}
return ret;
}

int* countBits(int n, int* returnSize){
*returnSize= n+1;
int *ret = malloc (sizeof(int)*(n+1));
for (int i=0;i<=n;i++)
{
ret[i]=count(i);
}
return ret;
}

ps. 可以縮短成
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* countBits(int n, int* returnSize){
*returnSize= n+1;
int *ret = calloc (n+1, sizeof(int));
for (int i=0;i<=n;i++)
{
int tmp=i;
while (tmp>0)
{
ret[i] += (tmp & 1);
tmp=tmp>>1;
}
}
return ret;
}

沒有留言:

張貼留言