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;
}
相关推荐
其实防守也摸鱼31 分钟前
个人学习 Pwn 思路:从基础到漏洞利用的进阶路径
大数据·前端·人工智能·chrome·算法·安全·网络安全
Nuanyt1 小时前
LeetCode Hot 100 链表专题(五)· 2 题(Java)
java·算法·leetcode·链表
§ꦿCFོ༉4 小时前
嵌入式八股—C语言入门学习(一)
c语言·编程语言·嵌入式八股文
w_zero_one4 小时前
递归算法(一)
java·开发语言·算法
圣保罗的大教堂4 小时前
leetcode 3736. 最小操作次数使数组元素相等 III 简单
leetcode
文丑颜不良啊5 小时前
LeetCode1881~1990题目解析
java·leetcode
沐晓时光5 小时前
C语言入门,字符串和字符串函数知识讲解
c语言·开发语言
风影同志783246 小时前
20 个比特能装下多少行情?——实测拆解 Kronos 的 K 线分词器
算法
写的都是BUG6 小时前
APK 里的钥匙,一直就放在门口:聊聊加固真正该做什么
前端·算法
地平线开发者7 小时前
CLIP 的零样本分类:一组文本如何变成图像分类器?
算法