Skip to content

Instantly share code, notes, and snippets.

@WOLOHAHA
Created July 26, 2014 10:09
Show Gist options
  • Select an option

  • Save WOLOHAHA/a9b4c723dd041ba58ea1 to your computer and use it in GitHub Desktop.

Select an option

Save WOLOHAHA/a9b4c723dd041ba58ea1 to your computer and use it in GitHub Desktop.
Given a positive integer, print the next smallest and the next largest number that have the same number of 7 bits in their binary representation.
package POJ;
public class Main{
/**
*
* 5.3 Given a positive integer, print the next smallest and the next largest
* number that have the same number of 7 bits in their binary representation.
*
*
*/
public int getNext(int n) {
//如果原始的数是: (for example)11011 00111 0011-->11011 00111 0101
// (for example)11011 00111 1100-->11011 01000 1111
//要得到大一点点的数,需要分配后边儿的1到前面进一位,其余的1都放到末尾去。
int c = n;
int c0 = 0;
int c1 = 0;
// compute c0 and c1
while (((c & 1) == 0) && (c != 0)) {
c0++;
c >>= 1;
}
while ((c & 1) == 1) {
c1++;
c >>= 1;
}
// Error: if n==11..1100..00, then there is no bigger number with the
// same number of 1s.
if (c0 + c1 == 0 || c0 + c1 == 31)
return -1;
int p = c0 + c1;
n |= 1 << p;
n &= ~(1 << (p) - 1);
n |= (1 << (c1 - 1)) - 1;
return n;
}
public int getPrev(int n){
//如果原始的数是: (for example)11011 00111 0011-->11011 00110 1110
// (for example)11011 00111 1100-->11011 00111 1010
//要得到小一点点的数,需要先把前位的1改为0,并把剩下的1尽可能地放前。
int c=n;
int c0=0;
int c1=0;
// compute c1 and c0
while((c&1)==1){
c1++;
c>>=1;
}
if(c==0)
return -1;
while((c&1)==0&&c!=0){
c0++;
c>>=1;
}
int p=c0+c1;
n&=(~0)<<(p+1);
int mask=(1<<(c1+1))-1;
n|=(mask<<(c0-1));
return n;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment