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(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.

Show Hint

Credits:
Special thanks to @ syedeefor adding this problem and creating all test cases.

解法一:

按照定义做,注意,x&(x-1)可以消去最右边的1

class Solution {
public:
vector<int> countBits(int num) {
vector<int> ret;
for(int i = ; i <= num; i ++)
ret.push_back(countbit(i));
return ret;
}
int countbit(int i)
{
int count = ;
while(i)
{
i &= (i-);
count ++;
}
return count;
}
};

解法二:

对于[2^k, 2^(k+1)-1]区间,可以划分成前后两部分

前半部分与[2^(k-1), 2^k-1]内的值相同,后半部分与[2^(k-1), 2^k-1]内值+1相同。

class Solution {
public:
vector<int> countBits(int num) {
vector<int> ret; ret.push_back();
if(num == )
// start case 1
return ret;
ret.push_back(); if(num == )
// start case 2
return ret; // general case
else
{
int k = ;
int result = ;
while(result- < num)
{
result *= ;
k ++;
}
// to here, num∈ [2^(k-1),2^k-1]
int gap = pow(2.0, k) - - num;
for(int i = ; i < k-; i ++)
{// infer from [2^i, 2^(i+1)-1] to [2^(i+1), 2^(i+2)-1]
// copy part
for(int j = pow(2.0, i); j <= pow(2.0, i+)-; j ++)
ret.push_back(ret[j]);
// plus 1 part
for(int j = pow(2.0, i); j <= pow(2.0, i+)-; j ++)
ret.push_back(ret[j]+);
}
for(int i = ; i < pow(2.0, k-) - gap; i ++)
{
int j = pow(2.0, k-) + i;
if(i < pow(2.0, k-))
// copy part
ret.push_back(ret[j]);
else
// plus 1 part
ret.push_back(ret[j]+);
}
}
return ret;
}
};

 

【LeetCode】338. Counting Bits (2 solutions)的更多相关文章

  1. 【leetcode】338 .Counting Bits

    原题 Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate t ...

  2. 【LeetCode】338. Counting Bits 解题报告(Python & Java & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目描述 Given a non negati ...

  3. 【LeetCode】75. Sort Colors (3 solutions)

    Sort Colors Given an array with n objects colored red, white or blue, sort them so that objects of t ...

  4. 【LeetCode】90. Subsets II (2 solutions)

    Subsets II Given a collection of integers that might contain duplicates, S, return all possible subs ...

  5. 【LeetCode】190. Reverse Bits 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 解题方法 二进制字符串翻转 位运算 日期 题目地址:https://le ...

  6. 【LeetCode】190. Reverse Bits

    题目: Reverse bits of a given 32 bits unsigned integer. For example, given input 43261596 (represented ...

  7. 【Leetcode】338. Bit位计数

    每次刷leetcode都有一种发现新大陆的感觉. 题目链接:https://leetcode-cn.com/problems/counting-bits/description/ 给定一个非负整数 n ...

  8. 【LeetCode】44. Wildcard Matching (2 solutions)

    Wildcard Matching Implement wildcard pattern matching with support for '?' and '*'. '?' Matches any ...

  9. 【LeetCode】130. Surrounded Regions (2 solutions)

    Surrounded Regions Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. A ...

随机推荐

  1. Java 第三章 选择结构1

    选择结构(一) 会使用基本的 if 选择结构 掌握逻辑运算符,掌握多重 if 选择结构 , 掌握嵌套 if 选择 结构 为什么需要 if 选择结构 例如: 如果张浩的 java 考试成绩大于 98分, ...

  2. .NET调用window串口读取电子秤的数据

    Private serialPort As SerialPort  '定义 Public Function CreateSerialPort() As String        Dim strWei ...

  3. 今天开始着手原来Office系统的重构

    原来系统架构Spring+Hibernate+Struts+springsecurity 拟改成 Spring+SpringMVC+MyBatis/JDBC+Shiro 同时优化前端的CSS和JQue ...

  4. [Leetcode][JAVA] Populating Next Right Pointers in Each Node II

    Follow up for problem "Populating Next Right Pointers in Each Node". What if the given tre ...

  5. [Leetcode][JAVA] Word Ladder II

    Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...

  6. node-restify简介

    restify 是Node.js的模块.虽然restify的API或多或少的参考了express,但restify不是一个MVC框架,它是一套为了能够正确构建REST风格API而诞生的框架. ###安 ...

  7. 手机端使用rem适配

    最近一直在做手机端的东西,各种型号的手机适配很是无解.经过同事及百度找到了这么一个方法 html font-size默认100px 将rem进行换算1px==0.01rem; 页面在各个手机适配个别会 ...

  8. PHP访问数据库

    1.原生mysql方式 <?php //最原生态的访问方式,不过SQL注入是个麻烦事 $con = mysql_connect("localhost","root& ...

  9. Dynamic CRM 2013学习笔记(八)过滤查找控件 (类似省市联动)

    我们经常要实现类似省市联动一样的功能,常见的就是二个查找控件,一个选择了省后,另一个市的查找控件就自动过滤了,只显示当前省下的市,而不是所有的市.当然这是最简单的,实际工作中还有更复杂的功能要通过过滤 ...

  10. Mac OS X上用CoreCLR运行一个真正的.NET控制台程序

    这个真正的控制台程序来自corefxlab,名叫CoreClrHelloWorld,是一个跨平台的.NET控制台演示程序,可以显示微软.Linux.苹果的logo. CoreClrHelloWorld ...