338. LeetCode_DP_Counting Bits
2016-04-25 00:29
411 查看
一、题目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 andreturn them as an array.Example:For
num = 5you 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.Hint:You should make use of what you have produced already.Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.Or does the odd/even status of the number help you in calculating the number of 1s?二、解题思路题目意思是找出0到输入数字之中,每个数字的二进制表示所含1的数目。例如5,从0到5,发现每个后一个数字都依赖于前面的某个数字的结果,通过二进制计算方式发现了规律;比如0,被2除后,余数为0;结果是0; (0个1)第一步,1被2除后,结果是0;余数是1;(未能整除) 再用得到的结果0,被2除,结果是0,而0为初始的结果; 所以就是初始的结果(0)+1=1(1的二进制表示共有1个1)。第二步,2被2除后,结果是1;余数是0;(能整除) 再用得到的结果1,被2除,发现第一步已经计算过了; 所以就是第一步的结果(1)(2的二进制表示共有1个1)。第三步,3被2除后,结果是1;余数是1;(未能整除) 再用得到的结果1,被2除,发现第一步已经计算过了; 所以就是第一步的结果(1)+1=2(3的二进制表示共有2个1)。第四步,4被2除后,结果是2;余数是2;(能整除) 再用得到的结果2,被2除,发现第二步已经计算过了; 所以就是第二步的结果(1)(4的二进制表示共有1个1)。第五步,5被2除后,结果是2;余数是1;(未能整除) 再用得到的结果1,被2除,发现第二步已经计算过了; 所以就是第二步的结果(1)+1=2 (5的二进制表示共有2个1)。所以结果就是
[0,1,1,2,1,2]
三、Java代码
public class Solution{public int[] countBits(int num){int[] dp = new int[num+1];dp[0] = 0;for (int i=1; i<=num; i++){if(i % 2 == 0)dp[i] = dp[i / 2];elsedp[i] = dp[i / 2] + 1;}return dp;}}
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树