第1个回答 2009-08-28
//恩,方法很多,上面的方法是可以的,我也提供一种方法
//忘了说一点,上面的方法没考虑负数
public class TestOne{
public static void getNum(int number){
String s = Integer.toBinaryString(number);
int num = 0;
for(int i=0;i<s.length();i++){
char sd = s.charAt(i);
if(sd=='1')num += 1;
}
System.out.println("十进制: "+number+"\n二进制: "+s+"\n二进制中1的个数: "+num);
}
//测试十进制数100的信息
public static void main(String args[]){
TestOne.getNum(100);
}
}本回答被提问者采纳
第2个回答 2009-08-28
有一种很方便的算法,利用了位运算..效率很高..
public class ConutOne {
// 用于计数的方法
public static int count(int num) {
int count = 0;
while (num != 0) {
num &= (num - 1);// 按位与操作
count++;
}
return count;
}
public static void main(String[] args) {
int num;
num = 101;
System.err.println(Integer.toBinaryString(num));// 展示该数字的二进制表示
System.err.println(count(num));// 输出1的个数
}
}
第3个回答 2009-08-28
public class A{
public static void main(String[] args){
print(25);//25是任意给的一个10进制数
}
public static void print(int n){
StringBuffer str=new StringBuffer();
int k=0;
while(n>0){
int i=n%2;
str=str.append(i);
if(i==1) k++;
n=n/2;
}
str=str.reverse();
System.out.println(n+"的2进制数是:"+str.toString());
System.out.println("1的个数是:"+k);
}
}