This one is really giving me a lot of hard time. So ultimately I decided to get some help from you guys. Perhaps, you can review it and tell me where I'm going wrong.
@
Basically:
Input = Number
- Convert it to binary String.
- Flip the bits (Set all 0's and reset all 1's)
- Output the Number you get by doing it.
I have hard-coded a number for now, as it was mentioned in the
question (= 2147483647)
0
public class FlippingBits {
private static String flipBits(String binaryOrig){
String flippedString = "";
for(int i = 0; i<binaryOrig.length(); i++){
if(binaryOrig.charAt(i) == '1')
flippedString += '0';
else
flippedString += '1';
}
return flippedString;
}
private static long getNum(String flippedString){
long new_number = 0;
for(int i = 0; i < flippedString.length(); i++){
new_number = (2*new_number) + (flippedString.charAt(i) - '0');
}
return new_number;
}
public static void main(String[] args) {
long num = 2147483647;
String numBinaryString = Long.toBinaryString(num);
String flippedString = flipBits(numBinaryString);
System.out.println(Long.toString(getNum(flippedString)));
}
};
Because Java doesn't have unsigned types, and interprets integers in two's complement form, You'll need to address both.
For the first point, we can use a
long to store the value. For the second point, we can bitmask with
0x00000000ffffffff and get the 32-bit part we want.
int original = 1; long flipped = ~original & 0x00000000ffffffffL; System.out.println(flipped); // outputs 4294967294
Java has tools to handle tasks like this as seen above - I wouldn't break out into
String manipulation unless I had to.