Search code examples
javabit-manipulationbitwise-operatorsbit-shift

Java shift operator don't works the same with a pre saved value than with the direct value


This comes up after solve the problem:

https://www.hackerrank.com/challenges/flipping-bits/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=miscellaneous

My solution is:

static long flippingBits(long n) {
    long l=0;                       //Have to pre-declare 0, Why?
    return (~l>>>32)&~n;
}

But what I wanted to do is use the 0 direct into the return statement instead of declaring it before in "long l", like this:

static long flippingBits(long n) {
    return (~0>>>32)&~n;            //Using 0 directly don't works.
}

I also tried with parenthesis but is the same. After testing looks like it is not able to shift if I put the 0 directly.

Why is giving me a different value?


Solution

  • This should be a fairly easy fix.
    return (~0>>>32)&~n;: the zero is interpreted as of type int.
    To tell the program it's of type long, write the following:
    return (~0L>>>32)&~n;