leetcode之Counting Bits

贴写的三种代码,当然最后一种是参考别人的代码

第一种:没有考虑分组:

mport java.util.Scanner;


public class Solution {
public static int[] countBits(int num) {
int[] sum = new int[num + 1];
for(int i = 0; i <= num; i++)
{
int count = 0;
int j = i;
while(j/2 >= 0 && j >0)
{
if(j != j/2*2)
count += 1;
j = j/2; 
}
sum[i]=count;
 
}
return sum;

}
public static void main(String args[])
{
Scanner n = new Scanner(System.in);
int num = n.nextInt();
int k = Integer.SIZE;
int[] sum = new int[num + 1];
sum = countBits(num);
for(int i =0; i <= num; i ++)
System.out.print(sum[i]);
 
}
       
   }

第二种考虑分组 (2的n次方倍):

import java.util.Scanner;


public class Solution {
public static int[] countBits(int num) {
int[] sum = new int[num + 1];
int k  = 1;
if(num ==0)
sum[0] = 0;
else if(num ==1)
sum[1] = 1;
 
else
{
sum[0] = 0;
sum[1] = 1;
int i = (int) Math.pow(2, k);
for( ; i + 1< (i*2) && i<=num; i +=2)
{
if(i == num)
sum[i]=sum[i/2];
else
{
sum[i]=sum[i/2];
sum[i+1]=sum[i/2]+1;
}
}
}

return sum;

}
public static void main(String args[])
{
Scanner n = new Scanner(System.in);
int num = n.nextInt();
int k = Integer.SIZE;
int[] sum = new int[num + 1];
sum = countBits(num);
for(int i =0; i <= num; i ++)
System.out.print(sum[i]);
 
}
       
   }

第三种:

import java.util.Scanner;


public class Solution {
public static int[] countBits(int num) {
int[] sum = new int[num + 1];
sum[0] =0;
for(int i = 0; i <= num; i++)
if(i%2 == 0)
sum[i] = sum[i/2];
else
sum[i] = sum[i/2]+1;

return sum;

}
}

阅读更多
个人分类: leetcode
上一篇leetcode
下一篇leetcode 260. Single Number III
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭