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 1:

Input: 2
Output: [0,1,1]

Example 2:

Input: 5
Output: [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.
Credits:

Special thanks to @ syedee for adding this problem and creating all test cases.

这道题给我们一个整数n,然我们统计从0到n每个数的二进制写法的1的个数,存入一个一维数组中返回,题目中明确表示不希望我们一个数字一个数字,一位一位的傻算,而是希望我们找出规律,而且题目中也提示了我们注意 [2-3], [4-7], [8-15] 这些区间的规律,那么我们写出0到 15 的数的二进制和1的个数如下:

-------------

-------------

-------------

-------------

我最先看出的规律是这样的,除去前两个数字0个1,从2开始,2和3,是 [21, 22) 区间的,值为1和2。而4到7属于 [22, 23) 区间的,值为 1,2,2,3,前半部分1和2和上一区间相同,2和3是上面的基础上每个数字加1。再看8到 15,属于 [23, 24) 区间的,同样满足上述规律,所以可以写出代码如下:

解法一:

class Solution {
public:
vector<int> countBits(int num) {
if (num == ) return {};
vector<int> res{, };
int k = , i = ;
while (i <= num) {
for (i = pow(, k - ); i < pow(, k); ++i) {
if (i > num) break;
int t = (pow(, k) - pow(, k - )) / ;
if (i < pow(, k - ) + t) res.push_back(res[i - t]);
else res.push_back(res[i - t] + );
}
++k;
}
return res;
}
};

下面来看一种投机取巧的方法,直接利用了 built-in 的函数 bitset 的 count 函数可以直接返回1的个数,题目中说了不提倡用这种方法,写出来只是多一种思路而已:

解法二:

class Solution {
public:
vector<int> countBits(int num) {
vector<int> res;
for (int i = ; i <= num; ++i) {
res.push_back(bitset<>(i).count());
}
return res;
}
};

下面这种方法相比第一种方法就要简洁很多了,这个规律找的更好,规律是,从1开始,遇到偶数时,其1的个数和该偶数除以2得到的数字的1的个数相同,遇到奇数时,其1的个数等于该奇数除以2得到的数字的1的个数再加1,参见代码如下:

解法三:

class Solution {
public:
vector<int> countBits(int num) {
vector<int> res{};
for (int i = ; i <= num; ++i) {
if (i % == ) res.push_back(res[i / ]);
else res.push_back(res[i / ] + );
}
return res;
}
};

下面这种方法就更加巧妙了,巧妙的利用了 i&(i - 1), 这个本来是用来判断一个数是否是2的指数的快捷方法,比如8,二进制位 1000, 那么 8&(8-1) 为0,只要为0就是2的指数, 那么我们现在来看一下0到 15 的数字和其对应的 i&(i - 1) 值:

i    binary ''  i&(i-)

-----------------------

-----------------------

-----------------------

-----------------------

我们可以发现每个i值都是 i&(i-1) 对应的值加1,这样我们就可以写出代码如下:

解法四:

class Solution {
public:
vector<int> countBits(int num) {
vector<int> res(num + , );
for (int i = ; i <= num; ++i) {
res[i] = res[i & (i - )] + ;
}
return res;
}
};

参考资料:

https://leetcode.com/problems/counting-bits/

https://leetcode.com/discuss/92796/four-lines-c-time-o-n-space-o-1

https://leetcode.com/discuss/92694/my-408-ms-c-solution-using-bitset

https://leetcode.com/discuss/92698/my-448ms-c-easy-solution-o-n-time-and-o-n-space

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Counting Bits 计数位的更多相关文章

  1. LeetCode Counting Bits

    原题链接在这里:https://leetcode.com/problems/counting-bits/ 题目: Given a non negative integer number num. Fo ...

  2. LeetCode——Counting Bits

    Question Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calcu ...

  3. Leetcode之动态规划(DP)专题-338. 比特位计数(Counting Bits)

    Leetcode之动态规划(DP)专题-338. 比特位计数(Counting Bits) 给定一个非负整数 num.对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数 ...

  4. 【LeetCode】338. Counting Bits (2 solutions)

    Counting Bits Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num  ...

  5. LN : leetcode 338 Counting Bits

    lc 338 Counting Bits 338 Counting Bits Given a non negative integer number num. For every numbers i ...

  6. 2016.5.16——leetcode:Reverse Bits(超详细讲解)

    leetcode:Reverse Bits 本题目收获 移位(<<  >>), 或(|),与(&)计算的妙用 题目: Reverse bits of a given 3 ...

  7. Week 8 - 338.Counting Bits & 413. Arithmetic Slices

    338.Counting Bits - Medium Given a non negative integer number num. For every numbers i in the range ...

  8. leetcode 上的Counting Bits 总结

    最近准备刷 leetcode  做到了一个关于位运算的题记下方法 int cunt = 0; while(temp) { temp = temp&(temp - 1);  //把二进制最左边那 ...

  9. leetcode 338. Counting Bits,剑指offer二进制中1的个数

    leetcode是求当前所有数的二进制中1的个数,剑指offer上是求某一个数二进制中1的个数 https://www.cnblogs.com/grandyang/p/5294255.html 第三种 ...

随机推荐

  1. 把PDF的底色改成护眼色,这样读起文章来就不是很累了······

    PDF格式背景改变方法如下: 打开PDF 点击 编辑 ->首选项->辅助工具->选中"替换文档颜色"和" 自定义颜色"->将背景颜色改成 ...

  2. MyCat源码分析系列之——SQL下发

    更多MyCat源码分析,请戳MyCat源码分析系列 SQL下发 SQL下发指的是MyCat将解析并改造完成的SQL语句依次发送至相应的MySQL节点(datanode)的过程,该执行过程由NonBlo ...

  3. TypeScript 强类型 JavaScript – Rafy Web 框架选型

    今天看到了 AngularJs 2.0 版本将基于 TypeScript 构建 的消息.与同事们对 TypeScript 展开了讨论.本文记录一些个人的想法. 理想的 JavaScript 开发模式 ...

  4. 01windows窗体程序学习

    静态用户名和密码的登录练习 private void button2_Click(object sender, EventArgs e) { textUser.Text = Convert.ToStr ...

  5. DateHelper.cs日期时间操作辅助类C#

    //==================================================================== //** Copyright © classbao.com ...

  6. Amazon Interview | Set 27

    Amazon Interview | Set 27 Hi, I was recently interviewed for SDE1 position for Amazon and got select ...

  7. servlet开发中遇到的问题集合

    问题1: servlet插入数据库时中文会乱码. 解决方法:在数据库连接地址最后增加两个转码参数(?useUnicode=true&characterEncoding=utf8) url=jd ...

  8. Web Worker javascript多线程编程(二)

    Web Worker javascript多线程编程(一)中提到有两种Web Worker:专用线程dedicated web worker,以及共享线程shared web worker.不过主要讲 ...

  9. 灵活的JavaScript(一)

    自己对JavaScript的原型,继承,闭包,多少也还是了解些,但是平时写的东西都挺简单的,也用不上,所以感觉提升不大.于是乎买了一本<JavaScript设计模式>来提高下自己,这本是百 ...

  10. CSS3之新UI方案

    border-radius 圆角 参数可为像素 也可为百分比 当一个参数时 作用范围为四个角 当两个参数时 作用范围为 左上右下 右上左下 当三个参数时 作用范围为 左上 右上左下 右下 当四个参数时 ...