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;
}
相关推荐
小李飞刀李寻欢16 小时前
DeepSeek V3 版本模型结构分析
算法·大模型·deepseek
某不知名網友16 小时前
C++ 七大排序算法完整讲解
java·算法·排序算法
:-)16 小时前
算法-希尔排序
数据结构·算法·排序算法
得物技术16 小时前
得物推荐系统诊断 Agent:从 “调接口” 到 “会思考”|AICon 演讲整理
人工智能·算法·架构
Lugas16 小时前
为啥说男生找对象尽量在25岁前找到?
算法
MrZhao40016 小时前
从能跑到可用:一个 Agent Harness 还差哪些工程闭环?
算法
薄情书生16 小时前
基于51单片机的电子钟设计(LCD12864显示 + DS1302)
c语言·51单片机·protues
QN1幻化引擎17 小时前
Gravity-Anchored Cognitive Field Architecture: The DalinX V8/V10 Implementation
java·前端·算法
半条-咸鱼17 小时前
【FreeRTOS】核心原理与实战速查手册
c语言·操作系统·rtos
白帽小阳17 小时前
Typora插件开发指南:打造专属IDE式写作环境
c语言·网络·python·网络安全·github·pygame·护网行动