Solution
public int gauss(int[] sequence) { long lastValue = sequence.length + 1; long total = (lastValue * (lastValue + 1)) / 2; long sum = 0L; for (int i=0; i < sequence.length; i++) { sum += sequence[i]; } return (int)(total - sum); }
NOTES:
- The long here was used for it be able to calc long sequences as within the range [0..100,000];
- In Java8 the loop to sum all values can be replaced for
Arrays.stream(sequence).sum();
, however, the performance will be lower - The assumption here is that the value is always missed because of it the code
sequence.length + 1
is to check if it is not the last one. (E.g [1,2,3,4] the result will be 5)
Mathematical Reference
NOTE: To know more about it search for Carl Gauss and the Sum of an Arithmetic Series.