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:
/**
 * 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;
}

相关推荐

  1. Atcoder ABC338 A - Capitalized?

    2024-02-19 14:48:03       53 阅读
  2. LeetCode //C - 338. Counting Bits

    2024-02-19 14:48:03       57 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-19 14:48:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-19 14:48:03       101 阅读
  3. 在Django里面运行非项目文件

    2024-02-19 14:48:03       82 阅读
  4. Python语言-面向对象

    2024-02-19 14:48:03       91 阅读

热门阅读

  1. C 练习实例69-约瑟夫环

    2024-02-19 14:48:03       61 阅读
  2. 微服务中4种应对跨库Join的思路

    2024-02-19 14:48:03       54 阅读
  3. 我的创作纪念日

    2024-02-19 14:48:03       52 阅读
  4. P1106 删数问题题解

    2024-02-19 14:48:03       47 阅读
  5. K8S更新部署docker的两种方法举例

    2024-02-19 14:48:03       56 阅读
  6. 设计模式三大原则

    2024-02-19 14:48:03       49 阅读
  7. 设计模式学习笔记 - 学前简述

    2024-02-19 14:48:03       41 阅读
  8. 设计模式的目的

    2024-02-19 14:48:03       49 阅读