Skip to content

Instantly share code, notes, and snippets.

@UncleGarden
Created July 29, 2014 05:00
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 UncleGarden/c77586fa5a7a12bff526 to your computer and use it in GitHub Desktop.
Save UncleGarden/c77586fa5a7a12bff526 to your computer and use it in GitHub Desktop.
CareerCup 150
/**
* 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.
*
* @author Garden
*/
public class CC5_3 {
public static void getNextBig(int n) {
int c = n;
int c0 = 0;
int c1 = 0;
while (((c & 1) == 0) && (c != 0)) {
c0++;
c = c >> 1;
}
while ((c & 1) == 1) {
c1++;
c = c >> 1;
}
if (c0 + c1 == 31 || c0 + c1 == 0) {
return;
}
int p = c0 + c1;
n = n | (1 << p);
n = n & (~((1 << p) - 1));
n = n | (1 << (c1 - 1)) - 1;
System.out.println(n);
System.out.println(Integer.toBinaryString(n));
}
public static void getNextSmall(int n) {
int c = n;
int c0 = 0;
int c1 = 0;
while (((c & 1) == 1) && (c != 0)) {
c1++;
n = n >> 1;
}
if (c == 0) {
return;
}
while (((c & 1) == 0) && (c != 0)) {
c0++;
c = c >> 1;
}
int p = c0 + c1;
n = n & ((~0) << (p + 1));
int mask = (1 << (c1 + 1)) - 1;
n = n | mask << (c0 - 1);
System.out.println(n);
System.out.println(Integer.toBinaryString(n));
}
public static void main(String[] args) {
getNextBig(13948);
getNextSmall(13948);
System.out.println("initial number:" + 13948);
System.out.println(Integer.toBinaryString(13948));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment