bankera ico

Spotify Puzzles: solving ReverseBinary in Java with just 1 line of code

Spotify proposes on its website some programming puzzle to be solved, for which it provides the input to be used for validate the proposed solution. The puzzles have different levels of difficulty and in this article I explain my solution for the first puzzle, the one with lower level of difficulty, called ReveseBinary.

The purpose of the exercise is to take as input an integer, convert it to the corresponding binary string, reverse this binary string and calculate the integer corresponding to this new bit sequence.

Example:
Input: 11 -> Binary String = 1011 -> Reversed Binary = 1101
Output = 13

All this in Java is very simple and can be done in a single line of code!

public class ReverseBinary {

	public static void main(String[] args) {
		// reading the input
		
		String input = null;
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			input = br.readLine();
		} catch (Exception e) {
			System.err.println("Error:" + e.getMessage()); }

		// here is the trick
		int output = Integer.parseInt(new StringBuilder(Integer.toBinaryString(Integer.parseInt(input))).reverse().toString(),2);    
		
		System.out.println(output);
	}
}

Submitting the program by email, you will receive an automated response indicating whether the answer was correct or not. In this case, as shown from the image below, mine was!

Schermata 2014-11-12 alle 21.13.27

But we see now in a more orderly way, highlighting the individual steps, what has been done:

public class ReverseBinary {

	public static void main(String[] args) {
		// lettura input		
		String input = null;
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			input = br.readLine();
		} catch (Exception e) {
			System.err.println("Error:" + e.getMessage()); }
			
		int x = Integer.parseInt(input);        // input string is parsed into an int value
		String s = Integer.toBinaryString(x);   // x value is converted into a binary string
		StringBuilder sb = new StringBuilder(s);// string is used to create a StringBuilder (because SB provides reverse() capabilities)
		sb = sb.reverse();                      // the StringBuilder is reversed
		s = sb.toString();						// we need a String because Integer.parseInt doesn't accept StringBuilder as input
		int output = Integer.parseInt(s,2); 	// the String is parsed into int, indicating that the rapresentation is binary
                                                        // (value 2 as second parameter)
                System.out.println(output);
       }
}
This entry was posted in $1$s. Bookmark the permalink.
bankera ico

Leave a Reply

Your email address will not be published. Required fields are marked *