Skip to content

Commit da4af2a

Browse files
committed
fix: clean up 0338-counting-bits.c
- Use calloc() instead of malloc() and memset(). - Use bit shifting instead of conditionally checking an offset.
1 parent 1349c24 commit da4af2a

File tree

1 file changed

+20
-17
lines changed

1 file changed

+20
-17
lines changed

Diff for: c/0338-counting-bits.c

+20-17
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,23 @@
11
/**
2+
* Given an integer n, return an array ans of length n + 1 such that for each i
3+
* (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.
4+
*
5+
* Constraints:
6+
*
7+
* 0 <= n <= 10^5
8+
*
29
* Note: The returned array must be malloced, assume caller calls free().
10+
*
11+
* Space: O(1)
12+
* Time: O(n)
313
*/
4-
int* countBits(int n, int* returnSize){
5-
// Initialize array of size n + 1
6-
int arraySize = n + 1;
7-
*returnSize = arraySize;
8-
int *dp = (int *)malloc(sizeof(int)*arraySize);
9-
memset(dp, 0, arraySize*sizeof(dp[0]));
10-
int offset = 1;
11-
12-
// Perform dp
13-
for (int i = 1; i <= n; i++) {
14-
if (offset * 2 == i) {
15-
offset = i;
16-
}
17-
dp[i] = 1 + dp[i - offset];
18-
}
19-
return dp;
20-
}
14+
15+
int *countBits(int n, int *returnSize) {
16+
int *ret = calloc(n + 1, sizeof(int));
17+
*returnSize = n + 1;
18+
19+
for (int i = 1; i <= n; ++i)
20+
ret[i] = ret[i >> 1] + (i & 1);
21+
22+
return ret;
23+
}

0 commit comments

Comments
 (0)