Search code examples
javabit-manipulationunary-operator

Hackkerrank BitFlipping Challenge


Most are probably familiar with this problem but for those who are not:

Given 32-bit unsigned integers flip their bits and print the resulting integers.

I was hoping that someone can give me clueson how to solve this in Java. Now I would normally provide some code i have tried but it was such a mess that it had to be deleted. I tried looking at the Editorial, which suggested using the bitwise ~ operator, but that didn't provide the required input. The example input/output was

Input:

3 (this is just the number of the integers that we are given)
2147483647 
1 
0

Output:

2147483648 
4294967294 
4294967295

P.S Any help would be appreciated.


Solution

  • There in nothing wrong with the ~ operator. It does flip the bits. All you have to understand, is that in Java, int value are always signed.

    But since “unsigned” is only a matter of interpretation of the bits, you have to print them like unsigned values, e.g. using Java 8:

    int[] values={2147483647, 1, 0};
    for(int value: values)
        System.out.println(Integer.toUnsignedString(~ value));
    

    will print

    2147483648
    4294967294
    4294967295
    

    If you can’t use Java 8, you can help yourself out by converting the int values to long before printing:

    int[] values={2147483647, 1, 0};
    for(int value: values)
        System.out.println((~ value) & 0xFFFFFFFFL);