【LeetCode】 338. Counting Bits

来源:互联网 发布:知乎 进小区发传单 编辑:程序博客网 时间:2024/06/05 02:41

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?

public class Solution {    public int[] countBits(int num) {        int[] res = new int[num + 1];        for (int i = 0; i <= num; i++) {            res[i] = Integer.bitCount(i);        }        return res;    }}

public class Solution {    public int[] countBits(int num) {        int result[] = new int[num + 1];        int offset = 1;        for (int index = 1; index < num + 1; ++index){            if (offset * 2 == index){                offset *= 2;            }            result[index] = result[index - offset] + 1;        }        return result;    }}


0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 联通全国流量包怎么办 缤智车钥匙丢了怎么办 车遮阳板松了怎么办 洗车把内饰划了怎么办 新车销售没销量怎么办 住院时间重叠了怎么办 长安cs75油耗高怎么办 墙内线烧了怎么办 如果没买票想进高铁站怎么办 老赖拒绝还款怎么办 gta5资产不兼容怎么办 平板黑屏闪退怎么办 施工证学历不够怎么办 隧道放炮声大怎么办 58工作被骗了怎么办 学历国家不承认怎么办 福州居住证一年到期怎么办 居住证过期2年怎么办 被房东坑了怎么办 房东违反了合同怎么办 上海居住证过期了怎么办 地铁卡消磁了怎么办 学生卡消磁了怎么办 家属院没房产证怎么办 邮箱收不到邮件怎么办 大学宿舍八人间怎么办 高中档案袋拆了怎么办 公派教师回国后怎么办? 事业单位辞职后档案怎么办 学信支付不了怎么办 校外怎么办北邮校园卡 报考身份证丢了怎么办 买房怎么办不取消低保 自考找不到真题怎么办 自考生考研没有档案怎么办 自考本科无学位怎么办 自考学位证书没拿到怎么办 自考毕业证出生日期错误怎么办 成考没有学位证怎么办 评职称学历认证怎么办 国家不承认学历怎么办