lc 338 Counting Bits


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

规律公式 Accepted

题干中提示可以利用时间复杂度仅为O(n)的方法来做,说明一定存在着某种规律,不需要把每个数进行除二取模累加这样死做。

经过分析,可以轻松地得知一个数i,它的二进制表示含有1的个数一定等于它除去倒数第一位之外剩余1的个数再加上最后一位是否为1。所以,可易得递推式:ans[i] = ans[i/2] + i%2,为了使得程序运行得更快,我们可以等价地用位运算去替代上式:ans[i] = ans[i >> 1] + (i & 1)

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

最新文章

  1. 网络IO之阻塞、非阻塞、同步、异步总结
  2. Andriod如何更改应用程序小图标
  3. 夺命雷公狗-----React---19--表单的值的修改
  4. UNITY5以后怎么改GUI文字
  5. 解决ng界面长表达式(ui-set)
  6. 关于cin,getchar(),scanf()的注意事项(转)
  7. 客户端用httpurlconnection来进行http连接的
  8. ANDROID_MARS学习笔记_S01_010日期时间控件
  9. linux文件权限详解
  10. Maven导入eclipse缺少web-resources目录
  11. php通过token验证表单重复提交
  12. BZOJ 3731 3731: Gty的超级妹子树 [树上size分块 !]
  13. TSQL:判定一段数组连续的数字段有多少的方案
  14. java 的序列化和反序列化的问题
  15. WPF 小小案列(同步异步)
  16. EntityFramework(1)基础概念与Database First
  17. 福州大学软件工程1816 | W班 第10次作业[个人作业——软件产品案例分析]
  18. Java如何判断文件或者文件夹是否在?不存在如何创建?
  19. z-tree学习笔记
  20. bzoj3514(主席树+lct)

热门文章

  1. 二级域名相同的情况下子页面调用父页面的js方法
  2. Redis官方文档资源
  3. Java发送邮件示例
  4. ios网络学习------11 原生API文件上传之断点续传思路
  5. Delphi中处理URL编码解码
  6. debug 和release 的区别
  7. J2SE基础:11.异常处理
  8. Android一些网站介绍
  9. 【Noip模拟By yxj】
  10. 【bzoj1260】[CQOI2007]涂色paint