Skip to content

Instantly share code, notes, and snippets.

@jyhjuzi
Created July 25, 2014 06:13
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 jyhjuzi/9c438422bcef5cceadab to your computer and use it in GitHub Desktop.
Save jyhjuzi/9c438422bcef5cceadab to your computer and use it in GitHub Desktop.
package Chapter5;
public class Q5_3{
public static void main(String[] arg){
int test1 = 0b001100111001111; // 001100111010111 // 001100110111110
System.out.println(Integer.toBinaryString(getNext(test1)));
System.out.println(Integer.toBinaryString(getPrevious(test1)));
int test2 = 0b001100000111100; // 001100001000111 // 1100000111010
System.out.println(Integer.toBinaryString(getNext(test2)));
System.out.println(Integer.toBinaryString(getPrevious(test2)));
}
static int getNext(int input){
int count0 = 0;
int count1 = 0;
if(input == 0)
return 0;
int temp = input;
while((temp&1) ==0){
count0++;
temp = temp >>1;
}
while((temp&1) ==1){
count1++;
temp = temp>>1;
}
// 111111000000 no bigger one31
// positive number
if(count1+count0 == 31)
return -1;
temp = temp | 1;
temp = temp << (count0 +count1);
int mask = (1<<(count1-1)) -1;
return mask | temp;
}
static int getPrevious(int input){
int temp=input;
int count0 =0;
int count1=0;
if(input == 0)
return 0;
while((temp & 1)==1){
count1++;
temp = temp >>1;
}
while((temp & 1 )==0){
count0++;
temp =temp>>1;
}
if(count1+count0==31)
return -1;
temp = temp &(~1);
temp = temp << (count0+count1);
int mask = (1<<(count1+1))-1;
mask = mask << (count0-1);
return mask | temp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment