will there be overflow or not in this case

22 Views Asked by At

I want to know that why there is no error in this code when I run it, especially in this line ret[(int) b[i]] = p;. Actually this solution I found in leetcode contest 387, user who got rank 3.

public int[] shrink(int[] a) {
  int n = a.length;
  long[] b = new long[n];
  for (int i = 0; i < n; i++) b[i] = (long) a[i] << 32 | i;
  Arrays.sort(b);
  int[] ret = new int[n];
  int p = 0;
  for (int i = 0; i < n; i++) {
    if (i > 0 && (b[i] ^ b[i - 1]) >> 32 != 0) p++;
    ret[(int) b[i]] = p;
  }
  return ret;
}

Explain this line ret[(int) b[i]] = p; why there is no overflow.

1

There are 1 best solutions below

0
Unmitigated On

According to §5.1.3. Narrowing Primitive Conversion:

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T.

That method is using a long to represent two integers, and casting the long to an int will retrieve the least significant 32 bits (which is the index in the original array).