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;
}
相关推荐
坚果派·白晓明8 分钟前
【鸿蒙PC三方库移植适配框架解读系列】第八篇:扩展lycium框架使其满足rust三方库适配
c语言·开发语言·华为·rust·harmonyos·鸿蒙
X journey24 分钟前
机器学习进阶(13):支持向量机SVM
算法·机器学习·支持向量机
洛水水42 分钟前
【力扣100题】30.二叉树的直径
算法·leetcode·职场和发展
gihigo19981 小时前
Bezier曲线曲面生成算法
算法
平行侠2 小时前
024多精度大整数 - 突破硬件精度限制的任意精度运算
数据结构·算法
谙弆悕博士2 小时前
快速学C语言——第16章:预处理
c语言·开发语言·chrome·笔记·创业创新·预处理·业界资讯
matlabgoodboy2 小时前
软件开发定制小程序APP帮代做java代码代编写C语言设计python编程
java·c语言·小程序
IronMurphy2 小时前
【算法四十五】139. 单词拆分
算法
洛水水3 小时前
【力扣100题】32.将有序数组转换为二叉搜索树
数据结构·算法·leetcode
handler014 小时前
UDP协议与网络通信知识点
c语言·网络·c++·笔记·网络协议·udp