0

Here is the situation, I have to cast from int to long and back to int from long. I am wondering whether I can avoid this casting.

long temp = (long) i + nums[i];  // i + nums[i] could be bigger than Integer.MAX_VALUE
                                 // i and nums[] both are int type.
int row = (int) (temp % 2);
int col = (int) (temp / 2);

Where row and col will be used to access an array later.

One change I could do for the row statement,

int row = (i%2 + nums[i]%2) % 2;

But I don't have any time-efficient implementation to replace the col statement so that I can avoid long casting for the first statement.

User_67128
  • 1,230
  • 8
  • 21
  • 2
    Why is `temp` a `long` at all? Are you expecting the value to overflow? – azurefrog Oct 28 '19 at 17:27
  • Yes, some cases i + nums[i] will be larger than Integer max. – User_67128 Oct 28 '19 at 17:31
  • If you're using java 8 you can use [java.lang.Math.toIntExact](https://stackoverflow.com/a/32869210/1361506). Other strategies in other answers may also be appropriate. – azurefrog Oct 28 '19 at 17:35
  • When you are adding 2 `int` values and assigning to `long`, you don't have to do explicit typecasting. From smaller data type to a larger one, Java does automatic type conversion. – Mathews Mathai Oct 28 '19 at 17:52
  • If you think i + nums[i] might be larger than max int then col is likely to be too. – onnoweb Oct 28 '19 at 18:23
  • 1
    @MathewsMathai The result of adding two integers is an integer. If there is overflow, this will be the wrong integer. Only then it is cast to long. Therefore the OP is right in casting one of the inputs first. – RealSkeptic Oct 28 '19 at 18:28
  • No, individually i and nums[i] are not greater than Integer.MAX_VALUE. So, col will be int. @onnoweb. – User_67128 Oct 28 '19 at 18:31
  • @onnoweb since you are adding two integers, each of them cannot be more than `Integer.MAX_VALUE`. Therefore, the maximum sum you could have is `2*Integer.MAX_VALUE`, which in itself is bigger than an int, but when divided by 2, will always be safe. – RealSkeptic Oct 28 '19 at 19:03
  • @ManojBanik Why do you want to avoid the cast? It may not be pretty, but it is essential. The first cast is needed to ensure that your addition is done in the `long` range, and your second is needed because you can't assign from a `long` to an `int` without a cast. – RealSkeptic Oct 28 '19 at 19:04
  • I am wondering if I could do it rightly and faster in another way @RealSkeptic, this is the reason. – User_67128 Oct 28 '19 at 19:13
  • Faster has nothing no to do with it. All a type cast does in this case is discard part of the expression's result when it assigns it. And anyway, only optimize for speed when you have speed issues. – RealSkeptic Oct 28 '19 at 23:27

0 Answers0