关闭

leetcode之Counting Bits

26人阅读 评论(0) 收藏 举报
分类:

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

第一种:没有考虑分组:

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;

}
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:188次
    • 积分:31
    • 等级:
    • 排名:千里之外
    • 原创:3篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档