5.4 Next Number

Be clear about how to clear or update or reset bits!!!

    public class program {
    public static int getNext(int n){
        int c = n, 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) return -1;
        int p = c0 + c1;//right most non-trailing zero;
        n |= (1<<p);
        // we clear bits to the right of p position
        int mask = ~((1<<p) - 1);
        n &=  mask;
        //rearrange 0 and 1;
        n |= (1<<(c1 - 1)) - 1;
        return n;
    }

    public static int getPrev(int n){
        int tmp = n, c0 = 0, c1 = 0;
        //find first non-trailing 1;
        while((tmp & 1) == 1){
            ++c1;
            tmp >>= 1;
        }
        if(tmp == 0) return -1;//all bits are 1;
        while(tmp != 0 && (tmp & 1) == 0){
            ++c0;
            tmp >>= 1;
        }
        int q = c0 + c1;// first non-trailing 1 we should flip it to 0;
        n &= ((~0) << (q+1));//clear from bits q onwards;
        //generate c1+1 1s: 1<<(c1+1) - 1;
        //shift those 1s to have c0 - 1 0s: ((1 << (c1+1)) - 1) << (c0 - 1);
        return n|((1 << (c1+1)) - 1) << (c0 - 1); 

    }


    public static void binPrint(int i) {
        System.out.println(i + ": " + Integer.toBinaryString(i));       
    }

    public static void main(String[] args) {
        int i = 13948;
        int p1 = getPrev(i);
        int n1 = getNext(i);
        binPrint(n1);
        binPrint(p1);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值