-1

Suppose I have an positive int x; I want to double x until it is larger than Integer.MAX_VALUE then stop.

I know MAX_VALUE = 2^31-1 and if x goes beyond this value, overflow occurs, and x becomes negative.

I'm wondering if I can use the condition (x < 0) to check if x goes beyond MAX_VALUE or not, because x is an integer, and it never goes beyond MAX_VALUE so I can't use (x > Integer.MAX_VALUE) to check.

Louis Tran
  • 1,154
  • 1
  • 26
  • 46

2 Answers2

1

Any (positive) number greater than half of the maximum will overflow if doubled, while doubling any number less than or equal to half of the maximum will result in a value less than or equal to the maximum. So This should work:

int sum = startValue;
int halfMax = Integer.MAX_VALUE / 2;
while ( sum <= halfMax ) {
   sum *= 2;
}

The loop starts at the given number, and if it is <= half the maximum, doubles the sum, exiting the loop as soon as sum becomes larger than half of the maximum.

FredK
  • 4,094
  • 1
  • 9
  • 11
0

Yes, it will always work because the maximum possible result on the last doubling is (-2^31 + (2^31 - 1)), which is -1. However, it's frowned upon to rely on overflow/underflow, since it's a side effect of how memory works, not an intended effect.

Greg Mc
  • 173
  • 1
  • 7