From 91167d0d3b7d15e9bf7365a79d7361be6de8087e Mon Sep 17 00:00:00 2001 From: Jeffrey Hsu Date: Fri, 5 Dec 2025 20:09:10 +0800 Subject: [PATCH] =?UTF-8?q?=E9=87=8D=E6=9E=84=20countBits=20=E5=87=BD?= =?UTF-8?q?=E6=95=B0=EF=BC=8C=E4=BF=AE=E5=A4=8D=E8=BF=94=E5=9B=9E=E5=80=BC?= =?UTF-8?q?=E5=B9=B6=E6=B7=BB=E5=8A=A0=20ASSERT=20=E5=AE=8F=E4=BB=A5?= =?UTF-8?q?=E5=A2=9E=E5=BC=BA=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/338.c | 37 ++++++++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/src/338.c b/src/338.c index 7001599..06da2a4 100644 --- a/src/338.c +++ b/src/338.c @@ -1,13 +1,44 @@ // // Created by aurora on 2024/9/16. // +#include #include +#include + +#define ASSERT(x, expect) \ + do \ + { \ + int retSize; \ + int *ret; \ + ret = countBits(x, &retSize); \ + for (int i = 0; i < retSize; i++) \ + assert(ret[i] == expect[i]); \ + free(ret); \ + } while (0) + int *countBits(int n, int *returnSize) { - return 0; + *returnSize = n + 1; + int *ret = (int *)malloc(sizeof(int) * (*returnSize)); + ret[0] = 0; + for (int i = 1; i <= n; i++) + { + ret[i] = ret[i >> 1] + (i & 1); + // equal to the following expression + // if (i % 2 == 0) + // ret[i] = ret[i / 2]; + // else + // ret[i] = ret[i - 1] + 1; + } + + return ret; } -int main() { - +int main() +{ + int t1[] = {0, 1, 1}; + ASSERT(2, t1); + int t2[] = {0, 1, 1, 2, 1, 2}; + ASSERT(5, t2); return 0; }