Created
February 21, 2013 23:33
-
-
Save traviskaufman/5009448 to your computer and use it in GitHub Desktop.
My Solution to Spotify's [Reversed Binary Numbers](https://www.spotify.com/us/jobs/tech/reversed-binary/) problem that's apparently wrong for reasons unknown to me. -_-
This file contains hidden or 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
import java.util.Scanner; | |
/** | |
* Class that contains logic to reverse the bits of an integer and spit it | |
* back out. | |
*/ | |
public class ReverseBinary { | |
/** | |
* Reverse the bits of an integer between 1 ≤ n ≤ 1000000000. | |
* i.e. 11 (1011) becomes 13 (1101) | |
* | |
* @param n The integer to reverse. | |
* @return The reversed integer. | |
*/ | |
public static int reverseBits(int n) { | |
// 1-indexed MSB Position | |
int msbPosition = findMSBPosition(n); | |
int reversed = 0; | |
for (int i = 0; i < msbPosition; i++) { | |
int mask = 1 << i; | |
int bit = (n & mask) >> i; | |
reversed |= (bit << (msbPosition - i - 1)); | |
} | |
return reversed; | |
} | |
/** | |
* Find the 1-indexed position of the MSB of a number. | |
* i.e. For the number 11 (1011), findMSBPosition() would return 4. | |
* | |
* @param n The number to find the MSB for. | |
* @return The 1-indexed position of the MSB. | |
* @protected | |
*/ | |
protected static int findMSBPosition(int n) { | |
int msbPos = 0; | |
int testNum = 1; | |
while (testNum <= n) { | |
msbPos++; | |
testNum <<= 1; | |
} | |
return msbPos; | |
} | |
/** | |
* Reads in a number and prints the bit-reversed number. | |
* | |
* @param args The arguments (which should just be one number). | |
*/ | |
public static void main(String[] args) { | |
// Check valid args | |
if (args.length != 1) { | |
System.exit(0); | |
} | |
Scanner sc = new Scanner(args[0]); | |
int n; | |
if (!sc.hasNextInt()) { | |
System.exit(0); | |
} | |
n = sc.nextInt(); | |
if (n < 1 || n > 1000000000) { | |
System.exit(0); | |
} | |
System.out.println("" + reverseBits(n)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment