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;
}
相关推荐
小璐资源网16 分钟前
C++中如何正确区分`=`和`==`的使用场景?
java·c++·算法
卢锡荣19 分钟前
LDR6021Q 车规级 Type‑C PD 控制芯片:一芯赋能,边充边传,稳驭全场景
c语言·开发语言·ios·计算机外设·电脑
N1_WEB23 分钟前
HDU:杭电 2018 复试真题汇总
算法
AMoon丶31 分钟前
C++模版-函数模版,类模版基础
java·linux·c语言·开发语言·jvm·c++·算法
We་ct38 分钟前
LeetCode 79. 单词搜索:DFS回溯解法详解
前端·算法·leetcode·typescript·深度优先·个人开发·回溯
眼眸流转1 小时前
LeetCode热题100(四)
算法·leetcode·职场和发展
相信神话20211 小时前
第零章:新手的第一课:正确认知游戏开发
大数据·数据库·算法·2d游戏编程·godot4·2d游戏开发
汀沿河1 小时前
2 模型预训练、微调、强化学习的格式
人工智能·算法·机器学习
码不停蹄Zzz1 小时前
C语言【结构体值传递问题】
c语言·开发语言
AMoon丶2 小时前
Golang--多种数据结构详解
linux·c语言·开发语言·数据结构·c++·后端·golang