Skip to main content

Practice ยท 5 of 5

Sum that refuses to overflow

Implement long sumTo(int n) returning 1 + 2 + ... + n. Then implement boolean fitsInInt(long total) returning whether the total can be stored in an int safely (compare against Integer.MAX_VALUE). sumTo(65_536) must NOT silently wrap (its true value exceeds Integer.MAX_VALUE).

Difficulty: beginner

Back to lesson: Practice: Practice: Types at Work