Created
July 29, 2014 05:00
-
-
Save UncleGarden/c77586fa5a7a12bff526 to your computer and use it in GitHub Desktop.
CareerCup 150
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
/** | |
* 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