LeetCode //C - 338. Counting Bits

338. Counting Bits

Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ansi is the number of 1's in the binary representation of i.

Example 1:

Input: n = 2
Output: 0,1,1
Explanation:

0 --> 0

1 --> 1

2 --> 10

Example 2:

Input: n = 5
Output: 0,1,1,2,1,2
Explanation:

0 --> 0

1 --> 1

2 --> 10

3 --> 11

4 --> 100

5 --> 101

Constraints:
  • 0 < = n < = 1 0 5 0 <= n <= 10^5 0<=n<=105

From: LeetCode

Link: 338. Counting Bits


Solution:

Ideas:

This function first allocates memory for an array of size n + 1 to store the counts. It initializes the first element of the array with 0, as the binary representation of 0 contains 0 ones. Then, for each number from 1 to n, it calculates the number of 1's based on the observation mentioned above. Specifically, it uses right shift (i >> 1) to divide the number by 2 and uses bitwise AND with 1 (i & 1) to determine if the number is odd (in which case one more 1 must be added). Finally, it returns the populated array and sets the return size to n + 1.

Caode:
c 复制代码
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* countBits(int n, int* returnSize) {
    *returnSize = n + 1; // Set the return size.
    int* ans = (int*)malloc((*returnSize) * sizeof(int)); // Allocate memory for the answer array.
    ans[0] = 0; // The number of 1's in 0 is 0.

    for (int i = 1; i <= n; i++) {
        // If i is even, then i and i/2 have the same number of 1's in their binary representation.
        // If i is odd, then i has one more 1 than i - 1 in its binary representation.
        ans[i] = ans[i >> 1] + (i & 1);
    }

    return ans;
}
相关推荐
人邮异步社区12 分钟前
C语言好学,还是Python好学?
c语言·开发语言·python
zx_7414848121 分钟前
YOLOv3 核心原理详解:Darknet-53 架构、多尺度预测与 FPN 特征融合
算法·yolo·目标检测·yolov3
MoRanzhi120321 分钟前
122.四平方和(暴力枚举)
python·数学·算法·蓝桥杯·完全平方数·暴力枚举·四平方和定理
倒头就睡的小比特22 分钟前
贪心算法介绍
算法·贪心算法
万少1 小时前
Qoder sonus模型 20分钟,复刻 马斯克 飞天汽车
前端·后端·算法
七牛云行业应用1 小时前
Muse Spark Open 发布:Meta 称其为美国最强开放权重模型,816B 参数如何落地
算法
esop轻Mes看板亮灯分拣ESD静电安2 小时前
产线“最后一米”的破局密码:ESOP与MES的区别与深度协同
算法
陈天伟教授2 小时前
《数据处理和标注技术》课程能力图谱
人工智能·算法
LMT_Lanmantech2 小时前
HyperWorks许可:almutil显示Unit满了,数据到底准不准?
运维·服务器·算法
禁默2 小时前
论文解读与思考:基于场所地图的标识感知机器人探索方法及工程参考的价值
人工智能·深度学习·算法·机器人