Given an integer, print the next smallest and next largest number that have the same
number of 1 bits in their binary representation
理解题意费了些时间。明白了之后就没什么难度了。答案没考虑负数的情况和无法找到这样的数字的情况,同时有一定的冗余。
#include <iostream>
#include <bitset>
using namespace std;
#define MAX_INDEX 30
bool getBit(int data, int i)
{
return (data & (1 << i)) >> i;
};
int setBit(int data, int i, bool v)
{
if(v)
{
return (data | (1 << i));
} else {
return (data & ~(1 << i));
}
};
int getNext(int d, bool isLarger)
{
int index = 0;
while(isLarger^getBit(d, index) && index <= MAX_INDEX)
{
index++;
};
while(!isLarger^getBit(d, index) && index <= MAX_INDEX)
{
index++;
}
if(index > MAX_INDEX)
{
cout<<"Can not find"<<endl;
return 0;
}
d = setBit(d, index--, isLarger);
d = setBit(d, index--, !isLarger);
int i=0;
while(index > i)
{
while(isLarger^getBit(d, index))
{
index--;
}
while(!isLarger^getBit(d, i))
{
i++;
}
if(index > i)
{
d = setBit(d, index, !isLarger);
d = setBit(d, i, isLarger);
}
}
return d;
};
int getNextLarger(int d)
{
if(d >= 0)
return getNext(d, true);
else
return -getNext(-d, false);
};
int getNextSmaller(int d)
{
if(d >= 0)
return getNext(d, false);
else
return -getNext(-d, true);
};
int main()
{
cout<<getNextLarger(4)<<endl<<getNextSmaller(4)<<endl;
cout<<getNextLarger(-4)<<endl<<getNextSmaller(-4)<<endl;
system("pause");
};