Skip to content

Instantly share code, notes, and snippets.

@traviskaufman
Created February 21, 2013 23:33
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 traviskaufman/5009448 to your computer and use it in GitHub Desktop.
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. -_-
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