Skip to content

Instantly share code, notes, and snippets.

@bitcpf
Created August 4, 2014 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitcpf/be3aee6d7a22ddd1a807 to your computer and use it in GitHub Desktop.
Save bitcpf/be3aee6d7a22ddd1a807 to your computer and use it in GitHub Desktop.
public class Q5_3 {
public static void main(String[] args){
int test = 0b11011001111111;
System.out.println(Integer.toBinaryString(test));
System.out.println(Integer.toBinaryString(getPrevious(test)));
System.out.println(Integer.toBinaryString(getNext(test)));
}
public static int getPrevious(int n){
if(n < 0) return -1;
int t= n;
int trailingonecnt = 0;
int zerocnt = 0;
// Find first trailing zeros
while(t > 0 && ((t & 1) == 1)){
t = t >> 1;
trailingonecnt ++;
}
if(t == 0) return -1;
// Find 10 part
while(t > 0 && ((t & 1) == 0))
{
t = t >> 1;
zerocnt ++;
}
int pos = zerocnt + trailingonecnt;
// Fill pos bit with one
n = n & (~0 << pos+1);
// System.out.println("inside");
// System.out.println("pos:"+pos);
// System.out.println(Integer.toBinaryString(n));
// Fill 1 on the right of the pos
int rstones = (1 << (trailingonecnt + 1)) - 1;
n = n | (rstones << (zerocnt -1));
return n;
}
public static int getNext(int n){
if(n < 0) return -1;
int t= n;
int trailingonecnt = 0;
int onecnt = 0;
// Find first trailing zeros
while(t > 0 && ((t & 1) == 0)){
t = t >> 1;
trailingonecnt ++;
}
if(t == 0) return -1;
// Find 10 part
while(t > 0 && ((t & 1) == 1))
{
t = t >> 1;
onecnt ++;
}
int pos = onecnt + trailingonecnt;
// Fill pos bit with 1
n = n | (1 << pos);
// Clear pos-1 to 0
int allones = ~0;
int mask = allones << (pos);
n = n & mask;
// Fill 1 on the right of the pos
int rstones = (1 << (onecnt-1)) - 1;
n |= rstones;
return n;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment