输入一个int型数据,计算出该int型数据在内存中存储时1的个数以及相应二进制表示

import java.util.Scanner;

/*
 * 输入一个int型数据,计算出该int型数据在内存中存储时1的个数。
 * 正数 补码为自己本身
 * 负数 是正数反码加1
 */
public class ClassTest06 {
	/*
	 * 正数补码 辗转相除
	 */
	public static String z(int a) {
		String str = "";
		int count = 0;
		while (a != 0) {
			int t = a % 2;
			a = a / 2;
			str = t + str;
		}
		return str;
	}

	/*
	 * 负数补码 
	 */
	/*public static String f(int a) {
		if(a==0){
			System.out.println("0000");
			return "0000";
		}
		String str = "";
		while (a != 0) {
			if ((a & 1) == 1) {
				str = "1"+str;
			}else{
				str = "0"+str;
			}
			a = a >>> 1;
		}
		System.out.println(str);
		return str;
	}
*/
	/*
	 * 用无符号右移判断1的个数
	 */
	public static int count(int a) {
		int count = 0;
		if (a == 0) {
			return count;
		}
		while (a != 0) {
			if ((a & 1) == 1) {//二进制与运算
				count++;
			}
			a = a >>> 1;//无符号右移
		}
		return count;
	}

	public static void main(String[] args) {
		System.out.println("请输入");
		Scanner sc = new Scanner(System.in);
		int a = sc.nextInt();
		int count = count(a);
		System.out.println("内存中" + count + "个1");
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值