栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

(3)二进制中1的个数

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

(3)二进制中1的个数

法1:

 知识点:

1< 
Scanner sc =new Scanner(System.in);
int N=sc.nextInt();


System.out.println(Integer.toString(N, 2));
//Integer.toString(int par1,int par2):par1表示 转成字符串的数字,par2表示 转成的进制表示
//Integer.toString(22,2):表示把22转成2进制表示的字符串,
int count =0;
//count来计数,比对每一位

for(int i=0;i<32;i++)
{
	if((N&(1< 

法2:

将N和1进行按位与运算,可以得出最低位

结果为1,最低位为1;

结果为0,最低位为0,然后循环将N右移一位进行运算。

int count =0;
for(int i=0;i<32;i++)
{
	if((N&1)!=0){count++;}
		N=N>>>1; //“>>>”表示无符号右移
}

法3:

思想:开始消除1,消除1的个数就是1的个数

最后一个1会往回借,而后面的0会全变成1   :8(1000) 减一得7(0111)

原数10100
原数-110011
原数&(原数-1)10000

 (x-1)&x 的效果就是 消去最低位的1

count =0;
while(N!=0)
{
	N=((N-1)&N);
	count++;
}
System.out.println(count);

完整代码:

法1:

import java.util.Scanner;
public class a {
	public static void main(String[] args) {
		Scanner sc =new Scanner(System.in);
		int N=sc.nextInt();
		System.out.println(Integer.toString(N, 2));
		int count =0;
		for(int i=0;i<32;i++)
		{
			if((N&(1< 

法2:

import java.util.Scanner;
public class a {
	public static void main(String[] args) {
		Scanner sc =new Scanner(System.in);
		int N=sc.nextInt();
		System.out.println(Integer.toString(N, 2));
		int count =0;
		for(int i=0;i<32;i++)
		{
			if((N&1)!=0){count++;}
				N=N>>>1; //“>>>”表示无符号右移
		}
		System.out.println(count);
	}
}

法3:

import java.util.Scanner;
public class a {
	public static void main(String[] args) {
		Scanner sc =new Scanner(System.in);
		int N=sc.nextInt();
		System.out.println(Integer.toString(N, 2));

		int count =0;
		while(N!=0)
		{
			N=((N-1)&N);
			count++;
		}
		System.out.println(count);
	}
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/867260.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号