当前位置 博文首页 > 求int型正整数在内存中存储时1的个数_JOKER in the hall的博客:

    求int型正整数在内存中存储时1的个数_JOKER in the hall的博客:

    作者:[db:作者] 时间:2021-09-20 13:57

    描述

    输入一个int型的正整数,计算出该int型数据在内存中存储时1的个数。

    输入描述:

    ?输入一个整数(int类型)

    输出描述:

    ?这个数转换成2进制后,输出1的个数

    示例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