Counting Bits
来源:互联网 发布:网络维护外包 编辑:程序博客网 时间:2024/06/05 03:18
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.
想法1:
比如 7 = 0111
7^4 = 0111^0100 = 0011
即7的1个数比3的1个数多1。
public int[] countBits(int num) { int[] dp = new int[num+1]; dp[0] = 0; int bit = 1; for(int i=1;i<=num;i++) { int k = (int) Math.pow(2, bit-1); if(i%k==0 && i/k==2){bit++;k*=2;} dp[i] = dp[i ^ k]+1; }// for(int i : dp){System.out.println(i);} return dp; }
想法2:
比如 7 = 0111
7^(7-1) = 0111&0110 = 0110
即7的1个数比6的1个数多1。
如果最低位是1,减一后则最低位为0, &后肯定会少一个1
如果最低位为0,最低位往前第一个为1的那一位x一定会变成0,&后x位少一个1
public int[] countBits(int num) { int[] dp = new int[num+1]; for(int i=1;i<=num;i++) { dp[i] = dp[i & (i-1)]+1; } return dp; }
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- Counting Bits
- 第三十五讲项目5——在北京买房
- 入门demo---Mybatis学习笔记(三)
- IIS部署ASP.NET网站
- 三子棋(C语言)
- 关于单片机下载通信
- Counting Bits
- UCGUI 消息机制实现分析
- 设计模式之建造者模式
- Hibernate核心接口和工作原理
- servlet的介绍和使用
- SSL学习
- 349/350. Intersection of Two Arrays
- [bzoj 1002] [FJOI2007]轮状病毒:数学,递推,高精度
- 16 :使用docker搭建hadoop分布式集群