Samarth Shah - 1 year ago 135
Java Question

# @HackerRank: FlippingBits. Wrong output

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.

@ https://www.hackerrank.com/challenges/flipping-bits

Basically:

Input = Number

1. Convert it to binary String.

2. Flip the bits (Set all 0's and reset all 1's)

3. Output the Number you get by doing it.

I have hard-coded a number for now, as it was mentioned in the
question (= 2147483647)

Problem is: It is giving me an output of:

0

Code:

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)));
}
};

Could anyone tell me what's wrong! This is after trying for 3-4 hours. Sorry if it's trivial.

EDIT: An excerpt from the Question:

"Take 1 for example, as unsigned 32-bits is

00000000000000000000000000000001

and doing the flipping we get

11111111111111111111111111111110

which in turn is 4294967294"

So, I'm having a feeling it has to do something with long being 64-bits. !?

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download