Created
July 25, 2014 06:13
-
-
Save jyhjuzi/9c438422bcef5cceadab to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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