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), ans[i] 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;
}
相关推荐
啊吧怪不啊吧14 小时前
二分查找算法介绍及使用
数据结构·算法·leetcode
知识搬运工人14 小时前
对比 DeepSeek(MLA)、Qwen 和 Llama 系列大模型在 Attention 架构/算法层面的核心设计及理解它们的本质区别。
算法
修行者Java15 小时前
JVM 垃圾回收算法的详细介绍
jvm·算法
AndrewHZ15 小时前
【图像处理基石】什么是光流法?
图像处理·算法·计算机视觉·目标跟踪·cv·光流法·行为识别
mjhcsp16 小时前
C++ 三分查找:在单调与凸函数中高效定位极值的算法
开发语言·c++·算法
立志成为大牛的小牛16 小时前
数据结构——四十二、二叉排序树(王道408)
数据结构·笔记·程序人生·考研·算法
Funny_AI_LAB18 小时前
李飞飞联合杨立昆发表最新论文:超感知AI模型从视频中“看懂”并“预见”三维世界
人工智能·算法·语言模型·音视频
RTC老炮21 小时前
webrtc降噪-PriorSignalModelEstimator类源码分析与算法原理
算法·webrtc
草莓火锅1 天前
用c++使输入的数字各个位上数字反转得到一个新数
开发语言·c++·算法
散峰而望1 天前
C/C++输入输出初级(一) (算法竞赛)
c语言·开发语言·c++·算法·github