# leetcode之Counting Bits

103人阅读 评论(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]);

}

}

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

个人资料
• 访问：415次
• 积分：33
• 等级：
• 排名：千里之外
• 原创：3篇
• 转载：0篇
• 译文：0篇
• 评论：0条
文章分类
文章存档
阅读排行