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);
}
}