编程之美2.1 求二进制数中1的个数

本文介绍四种计算二进制数中1的数量的方法:使用求余操作、位操作、n与n-1的与运算及预先计算0-255范围内的1数量并存储在数组中。
//题目: 求二进制数中1的个数
public class Main {

	public static void main(String[] args) {
		System.out.println(getOneCount1(19));
		System.out.println(getOneCount2(19));
		System.out.println(getOneCount3(19));
	}

	// 解法1: 使用求余操作	O(log2N)
	public static int getOneCount1(int n) {
		int result = 0;
		while (n != 0) {
			if (n % 2 == 1) {
				result++;
			}
			n = n / 2;
		}
		return result;
	}
	
	//解法2: 使用位操作	O(log2N)
	public static int getOneCount2(int n){
		int result = 0;
		while(n!=0){
//			if((n&1) == 1){
//				result++;
//			}
			result = result+(n&1);
			n = n>>1;
		}
		return result;
	}
	
	//解法3: 使用n与n-1与运算的方式	O(M),M为1的个数
	public static int getOneCount3(int n){
		int result = 0;
		while(n!=0){
			n = n&(n-1);
			result++;
		}
		return result;
	}
	
	//解法4: 使用分支操作把0-255种情况全都列举出来,然后根据条件直接返回结果	O(1)
	//解法5: 把0-255各有多少个1提前存在数组中,根据数字直接返回结果	O(1)
	//4,5解法属于以空间换时间

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值