蓝桥 二进制中1的个数 JAVA

请实现一个函数,输入一个整数,输出该数二进制表示中1的个数
例如:9的二进制表示为1001,有2位是1

先看结果:输入9 输出它的二进制 运用位运算方法&与,得出1有两位
9
1001
2
2

public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int N = scanner.nextInt();
		System.out.println(Integer.toString(N, 2));

		int count = 0;		
		for (int i = 0; i < 32; i++) {
			// 比对每一位
			if ((N & (1 << i)) == (1 << i)) {
				count++;                           // 第一种方法
			}
		}
		System.out.println(count);

		
		count = 0;
		while (N != 0) {
			N = ((N - 1) & N);        // &与
			count++;                               // 第二种方法
		}
		System.out.println(count);
	}

小剧场:暴富的方法都写在刑法里了…

发布了161 篇原创文章 · 获赞 120 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43771695/article/details/104816826