1. 程式人生 > >LeetCode 給定一個非負整數 num。對於 0 ≤ i ≤ num 範圍中的每個數字 i ,計算其二進位制數中的 1 的數目並將它們作為陣列返回。

LeetCode 給定一個非負整數 num。對於 0 ≤ i ≤ num 範圍中的每個數字 i ,計算其二進位制數中的 1 的數目並將它們作為陣列返回。

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* countBits(int num, int* returnSize) {
    printf("num:%d \n",num);
    int n = num +1;
    int *  p =NULL;

    if(num == 0)

{

*returnSize =0;
        return p;

}

p = (int*)malloc(sizeof(int)*n);
    
    p[0] = 0;
    *returnSize =n;

    
    for(int i = 1;i<=num;i++)
    {
        int m = 0;
        int k = i;
        while(k)
        {
           k=k&(k-1);
            m ++ ;
        }
        p[i] = m;
    }
    return p;
}

思考:

returnSize:返回 陣列總大小!

*returnSize =num + 1;(包括 0)

函式裡:

當輸入num=0; 返回 空指標就好。

計算 一個數的二進位制中的 1的個數 就是

while(k)

{

k = k&(k-1);

count++;

}