LeetCode--338. Counting Bits

对于整型数i,计算0-i范围的每个数的二进制表达中含有1的数目,很显然假设k的二进制表达中含有1的数目为f(k),k+1的二进制表达中含有1的数目为f(k+1)必然与前面算过的f(i)相关,显然是用动规解决。

经过分析发现:

LeetCode--338. Counting Bits_第1张图片

public static int[] countBits(int num) {
		
		int max=(int) (Math.log10(Integer.MAX_VALUE)/Math.log10(2.0));
		int[] powerOf2=new int[max+1];
		for(int i=0;i<=max;i++)
			powerOf2[i]=(int)Math.pow(2, i);
		int p=1;
		int[] ans=new int[num+1];
		ans[0]=0;ans[1]=1;ans[2]=1;
		for(int k=3;kpowerOf2[p] && k		
		int max=(int) (Math.log10(Integer.MAX_VALUE)/Math.log10(2.0));
		int[] powerOf2=new int[max+1];
		for(int i=0;i<=max;i++)
			powerOf2[i]=(int)Math.pow(2, i);
		int p=1;
		int[] ans=new int[num+1];
		ans[0]=0;ans[1]=1;ans[2]=1;
		for(int k=3;kpowerOf2[p] && k 
  

 

你可能感兴趣的:(LeetCode--338. Counting Bits)