程序员面试金典——5.3最接近的数

程序员面试金典——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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值