给定整数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;
}