博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode: Counting Bits
阅读量:7210 次
发布时间:2019-06-29

本文共 1014 字,大约阅读时间需要 3 分钟。

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(n*sizeof(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.

Hint:

  1. You should make use of what you have produced already.
  2. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
  3. Or does the odd/even status of the number help you in calculating the number of 1s?
1 public class Solution {2     public int[] countBits(int num) {3         int[] res = new int[num+1];4         for (int i=1; i<=num; i++) {5             res[i] = res[i>>1] + (i&1);6         }7         return res;8     }9 }

 

转载地址:http://porum.baihongyu.com/

你可能感兴趣的文章
vue.js实现原理 -- 订阅者,发布者模式
查看>>
填坑-十万个为什么?(19)
查看>>
vue 使用svg图片 svg-sprite-loader
查看>>
idea实用插件
查看>>
iOS应用签名(下)
查看>>
【译】ObjectBox官方文档(6)——ObjectBox与Kotlin
查看>>
深入学习Activity生命周期
查看>>
168 Excel Sheet Column Title
查看>>
HTML学习--空元素
查看>>
未来三年人工智能将融入日常生活
查看>>
Django搭建个人博客:使用 Bootstrap 4 改写模板文件
查看>>
React Hooks 可以为我们带来什么,及为什么我觉得React才是前端的未来
查看>>
Spring Boot 实现定时任务的 4 种方式
查看>>
Astute Ex对区块链项目深度挖掘和发展
查看>>
一个简单的 命令行 图片压缩工具
查看>>
JavaScript之来龙去脉(一)
查看>>
区块链给我们带来什么(一)数字货币
查看>>
深度学习概论(Andrew NG 深度学习课程笔记(一))
查看>>
程序员等级说明书
查看>>
令人心动的HTTP知识点大全
查看>>