Skip to content

Commit

Permalink
Create: 338-Counting-Bits.c
Browse files Browse the repository at this point in the history
  • Loading branch information
Ykhan799 authored Sep 4, 2022
1 parent 748742c commit 8652eff
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions c/338-Counting-Bits.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* countBits(int n, int* returnSize){
// Initialize array of size n + 1
int arraySize = n + 1;
*returnSize = arraySize;
int *dp = (int *)malloc(sizeof(int)*arraySize);
memset(dp, 0, arraySize*sizeof(dp[0]));
int offset = 1;

// Perform dp
for (int i = 1; i <= n; i++) {
if (offset * 2 == i) {
offset = i;
}
dp[i] = 1 + dp[i - offset];
}
return dp;
}

0 comments on commit 8652eff

Please sign in to comment.