求int型正整数在内存中存储时1的个数

https://www.nowcoder.com/practice/440f16e490a0404786865e99c6ad91c9?tpId=37&tqId=21238&tPage=1&rp=&ru=%2Fta%2Fhuawei&qru=%2Fta%2Fhuawei%2Fquestion-ranking

一、题目描述

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

二、代码实现

如果输入是正数,则必须使用>>>来右移一位,这样在高位的左边补充的是0(负数进行>>运算时在左边高位补充的是1)。

import java.util.Scanner;
//遍历次数为最左边的1所在位置(最右边的位为第一个)
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        while (sc.hasNextInt()) {
            int input = sc.nextInt();
            
            int countOfOne = 0;
            while (input > 0) {
                //if (input%2 == 1) {
                //
                //if (input & 1 == 1) {
               //error: bad operand types for binary operator '&'
                if ((input & 1) == 1) {
                    countOfOne++;
                }
                //input = input / 2;
                //
                //input = input >> 1;
                //如果输入可以是负数,那么这里必须使用>>>
                input = input >>> 1;
            }
            
            System.out.println(countOfOne);
        }
        
    }
}

另一种方式:

import java.util.Scanner;
//迭代次数为二进制中为1的位的个数
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        while (sc.hasNextInt()) {
            int input = sc.nextInt();
            
            int countOfOne = 0;
            while (input > 0) {
                countOfOne++;
                input = input & (input - 1);    //每一次消去最低位的1,有多少个1就迭代多少次
            }
            
            System.out.println(countOfOne);
        }
    }

}

使用API得到整数的二进制字符串表示形式:

import java.util.Scanner;
//遍历次数为最左边的1所在位置(最右边的位为第一个)
public class Main {
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        while (sc.hasNextInt()) {
            int input = sc.nextInt();
            String binaryStr = Integer.toBinaryString(input);
            
            int countOfOne = 0;
            //for (int i=0; i<32; i++) {
            //存在数组越界等非法访问情况
            for (int i=0; i<binaryStr.length(); i++) {
                if (binaryStr.charAt(i) == '1') {
                    countOfOne++;
                }
            }
            
            System.out.println(countOfOne);
        }
    }
}
发布了62 篇原创文章 · 获赞 30 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/sinat_30973431/article/details/104045716