当前位置 博文首页 > 求int型正整数在内存中存储时1的个数_JOKER in the hall的博客:
输入一个int型的正整数,计算出该int型数据在内存中存储时1的个数。
?输入一个整数(int类型)
?这个数转换成2进制后,输出1的个数
输入:5
输出:2
方法一:
import java.util.Scanner;
public class Main{
? ? public static void main(String[] args) {
? ? ? ? Scanner sc=new Scanner(System.in);
? ? ? ? int num=sc.nextInt();
? ? ? ? int count=Integer.bitCount(num);
? ? ? ? System.out.println(count);
? ? }
}
方法二:
import java.util.Scanner;
public class Main {
? ? public static void main(String[] args) {
? ? ? ? Scanner sc=new Scanner(System.in);
? ? ? ? int number=sc.nextInt();
? ? ? ? int count = 0;
? ? ? ? while (number != 0) {
? ? ? ? ? ? if (number % 2 != 0) {
? ? ? ? ? ? ? ? count++;
? ? ? ? ? ? }
? ? ? ? ? ? number = number / 2;
? ? ? ? }
? ? ? ? System.out.println(count);
? ? }
}
?
?
?
cs