my dynamic solution using C


  • 0
    M

    /**

    • Return an array of size *returnSize.

    • Note: The returned array must be malloced, assume caller calls free().
      /
      int
      countBits(int num, int* returnSize) {
      int* result = (int*)malloc(sizeof(int)*(num+1));
      if (num < 2){
      for (int i = 0; i < num+1; i++) result[i] = i;
      *returnSize = num+1;
      return result;
      }
      for (int i = 0; i < 2; i++) result[i] = i;
      int i = 2;
      for (int j = 1, k = 2; i <= num; i++, j++){
      if (j > k){
      k = k * 2;
      j = 1;
      }
      result[i] = result[i-k]+1;
      }
      *returnSize = i;

      return result;
      }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.