0

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?

  • 1
    Because `~0` is an `int` and `long l = 0;` is a `long`. You can use `~0L` instead. – Jacob G. Apr 17 '20 at 17:59
  • 1
    The task is much easier when using `int`. Use [`parseUnsignedInt`](https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#parseUnsignedInt-java.lang.String-) to parse the input to an `int`, flip the bits via `~i` and print the result using [`toUnsignedString`](https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#toUnsignedString-int-). – Holger Apr 22 '20 at 11:03

2 Answers2

1

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;

itzFlubby
  • 2,269
  • 1
  • 9
  • 31
0

On a related note, shorts and bytes are treated similarly.

byte b =-16; // 1111000
b = (byte)(b>>>1);
System.out.println(b); //prints -8 and not 120

ANDing with 0xFF solves the problem

b = -16;
b = (byte)((b&0xFF)>>1);
System.out.println(b); // prints 120 as expected.

The reason is that b is converted to an int first and then shifted.

On a different note, if n is a long, why did you not just use ~n to flip bits since that is all that is needed?

WJS
  • 36,363
  • 4
  • 24
  • 39