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].
Follow up:
It is very easy to come up with a solution with run time O(nsizeof(integer))*. But can you do it in linear time O(n) /possibly in a single pass?

Space complexity should be O(n).
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

public class Solution {
    public int[] countBits(int num) {
        if(num == 0){
            return new int[]{0};
        }
        int dp[] = new int[num+1];
        dp[0] = 0;
        dp[1] = 1;
        for(int i = 2 ; i<=num; i++){
            if((i & 1) == 1){
                dp[i] = dp[i>>1] + 1;
            }else{
                dp[i] = dp[i>>1];
            }
        }
        return dp;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,357评论 0 33
  • Correctness AdapterViewChildren Summary: AdapterViews can...
    MarcusMa阅读 12,875评论 0 6
  • 经常有人问我几年职场生涯下来,对我帮助最大的职业习惯是什么?认真思索后,如果只能推荐一种的话,我觉得应该是脱胎于P...
    henu王凯阅读 6,291评论 4 68
  • 一、前言 项目中经常会遇到要自定义slider,而通常意义上的自定义一般的有两种: 二、正文 当然小白今天想要介绍...
    deepindo阅读 2,828评论 0 1

友情链接更多精彩内容