相同bit1的最大的数

给定整数n,求出和n 的bit 1的数量相同的,并且大于n的最小值,或者小于n的最大值



这个题目的思路和给定2134,求相同数字的大于2134的最小值思路一样,都是从后往前找,找到第一次遇到的数字下降,然后再从后往前,找到第一个大于这个数字的数,然后交换,然后从下降位置之后的所有数字从小到大排序


求小于2134的最大值,从后往前找,第一次遇到数字上升的位置i, 再从后往前找第一个小于位置i上的数字,交换,将i位置之后的所有数字,从大到小排序



这道题目的技巧在于,都是01的变换,少了排序的步骤,只需要计算在后面部门的1的数量,然后讲这些1放在最后,或者放在前面,即可


//Given an integer, print the next smallest and next largest 
//number that has the same number of 1 bits in their binary representation.

unsigned int GetNextBig(unsigned int x)
{
	int i = 0;
	bool bOne = false;
	int nCount = 0;
	unsigned int uRet = x;

	//find the first pattern like "01"
	for (; i < 32; i++)
	{
		bool bBitOne = ((uRet & (1 << i)) != 0); // failed at (uRet & (1 << i) != 0)
		nCount = bBitOne ? nCount + 1 : nCount; //count the bit ones
		uRet &= ~(1 << i); //clear bit ones
		bOne = bOne || bBitOne; //previous met bit one?
		if (!bBitOne && bOne) //break condition, "01"
			break;
	}

	if (i >= 32) return x; //biggest already

	uRet |= (1 << i); //make current 0 to 1
	nCount--; //need to add continuous nCount-1 to the tail
	
	//add continuous nCount-1 to the tail
	unsigned int uMask = 0;
	for (int j = 0; j < nCount; j++)
		uRet |= (1 << j);

	return uRet;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值