Last active
December 28, 2015 16:28
-
-
Save pedrotoliveira/1b85c18367547f368827 to your computer and use it in GitHub Desktop.
Flipping bits
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
import java.io.*; | |
import java.util.*; | |
public class Solution { | |
public static void main(String[] args) { | |
Scanner in = new Scanner(System.in); | |
int testCases = in.nextInt(); | |
for (int i=0; i< testCases; i++) { | |
if (in.hasNextLong()) { | |
long number = in.nextLong(); | |
//System.out.println("Number: \n" + number); | |
String binaryString = Long.toBinaryString(number); | |
//System.out.println("Binary String: \n" + binaryString); | |
System.out.println(new FlippingBits(binaryString).flip()); | |
} else { | |
throw new RuntimeException( | |
"We have some input problem. [testCases=" + testCases + " i=" + i + "]"); | |
} | |
} | |
} | |
} | |
class FlippingBits { | |
private final char[] bits; | |
public FlippingBits(final String binaryString) { | |
this.bits = new char[32]; | |
Arrays.fill(this.bits, 0, 32, '0'); | |
char[] binary = binaryString.toCharArray(); | |
int startPos = 32 - binary.length; | |
System.arraycopy(binary, 0, this.bits, startPos, binary.length); | |
//System.out.println("Bits: \n" + new String(this.bits)); | |
} | |
public Long flip() { | |
char[] flipped = new char[32]; | |
for (int i=0; i < this.bits.length; i++) { | |
flipped[i] = this.bits[i] == '0' ? '1' : '0'; | |
} | |
//System.out.println("Flipped: \n" + new String(flipped)); | |
return Long.valueOf(new String(flipped), 2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment