338. Counting Bits
来源:互联网 发布:网络大电影票房排行榜 编辑:程序博客网 时间:2024/05/16 01:27
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]
.
第一种方法很直接,本来以为不会通过的,结果直接ac了
public class Solution { public int[] countBits(int num) { int[] res=new int[num+1]; int j=0,n=0; for(int i=0;i<=num;i++){ n=i; for(j=0;n>0;j++){ n&=(n-1); } res[i]=j; } return res; }}
第二种是discuss里的方法,在增加一位的情况下,不断的将之前的结果加1.
public class Solution { public int[] countBits(int num) { int[] res=new int[num+1]; res[0]=0; int i,pow=1,t; for(i=1,t=0;i<=num;i++,t++){ if(i==pow){ pow*=2; t=0; } res[i]=res[t]+1; } return res; }}
0 0
- [leetcode] 338. Counting Bits
- 338. Counting Bits
- leetcode 338. Counting Bits
- LeetCodeOJ:338. Counting Bits
- [LeetCode]338. Counting Bits
- LeetCode#338. Counting Bits
- 338. Counting Bits
- [LeetCode] 338. Counting Bits
- LeetCode 338. Counting Bits
- 338. Counting Bits
- [LeetCode]338. Counting Bits
- LeetCode-338. Counting Bits
- LeetCode *** 338. Counting Bits
- 338. Counting Bits
- (leetcode) 338. Counting Bits
- Swift 338. Counting Bits
- #leetcode#338. Counting Bits
- LeetCode 338. Counting Bits
- Add Two Numbers
- Java应用梯度下降求解线性SVM模型参考代码
- psi and index do not match问题
- 人脸识别
- Python网络数据采集(1)
- 338. Counting Bits
- hdu3094—A tree game-(树形博弈)
- android 之popupWindow 在指定位置上的显示
- CentOS7 下配置svn的安装及基础配置介绍
- linux shell 命令替换 变量替换
- SSH框架之Hibernate的懒加载
- 工作日志
- animated `useNativeDriver` is not supported because the native animated module is missing
- java系统高并发解决方案之图片服务器分离