程序员面试金典——5.3最接近的数
Solution1:把问题想的太简单了,参考书上答案(P166-P170)如下:
书上的思路和算法就很好啊~
class CloseNumber {
public:
vector<int> getCloseNumber(int x) {
// write code here
vector<int> res;
int smaller = getSmaller(x), bigger = getBigger(x);
res.push_back(smaller);
res.push_back(bigger);
return res;
}
int getBigger(int n) {
int c = n, res = 0, c0 = 0, c1 = 0;
while(((c & 1) == 0) && (c != 0)) {
c0++;
c >>= 1;
}
while((c & 1) == 1) {
c1++;
c >>= 1;
}
if(c0 + c1 == 31 || c0 + c1 == 0) //1111...000这种数无更大值(首位是符号位)
return -1; //0这个数无较小数
res = n + (1 << c0) + (1 << (c1 - 1)) - 1;
return res;
}
int getSmaller(int n) {
int c = n, res = 0, c0 = 0, c1 = 0;
while((c & 1) == 1) {
c1++;
c >>= 1;
}
if(c == 0) //像7(111)这类数无较小值
return -1;
while(((c & 1) == 0) && (c != 0)) {
c0++;
c >>= 1;
}
if(c0 + c1 == 31 || c0 + c1 == 0) //1111...000这种数无更大值(首位是符号位)
return -1; //0这个数无较小数
res = n - (1 << c1) - (1 << (c0 - 1)) + 1;
return res;
}
};