[LeetCode]338. Counting Bits

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.

Example:For num = 5, you should return [0,1,1,2,1,2].

题目

给定一个非负整数num,计算出从0到num的每个数的二进制中包含1的个数

方法

对于数字n,它二进制表示形式中1的个数bits[n] = bits[n>>1]+n&1

c代码

#include <assert.h>
#include <stdlib.h>

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* countBits(int num, int* returnSize) {
    int i = 0;
    int* bits = (int *)malloc(sizeof(int) * (num+1));
    bits[0] = 0;
    for(i = 0; i <= num; i++) {
        bits[i] = bits[i>>1] + (i&1);
    }
    *returnSize = num+1;
    return bits;
}

int main() {
    int returnSize = 0;
    int* bits = countBits(5, &returnSize);
    assert(bits[0] == 0);
    assert(bits[1] == 1);
    assert(bits[2] == 1);
    assert(bits[3] == 2);
    assert(bits[4] == 1);
    assert(bits[5] == 2);
    assert(returnSize == 6);

    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,349评论 0 33
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,898评论 18 399
  • “小勇在北京有过一个女朋友,两个人还意外有过一个孩子,其实都商量好要结婚了,后来女方突然反悔了,擅作主张就把孩子打...
    老肆阅读 2,713评论 0 0
  • 过分的离别,不是在伤悲中进行,而是在你猝不及防时回放。 笔触悬在纸张上面,良久,只字未写,突然而来的离别回放,宛如...
    风月小笺阅读 3,077评论 0 2
  • GSS_3cb6阅读 955评论 0 0