2 ms·
The given answer to #1 is incorrect. It proposes to find the missing number in a range 1, 2, 3, ..., N by computing the sum of 1+2+3+...+N and then subtracting
by ken 8y ago
The given answer to #1 is incorrect.
It proposes to find the missing number in a range 1, 2, 3, ..., N by computing the sum of 1+2+3+...+N and then subtracting the sum of the given numbers. It tries to use the old Gauss formula Nx(N+1)/2, but gets the implementation wrong:
int expectedSum = totalCount * ((totalCount + 1) / 2);
In Java, of course, "/" means "divide by 2 and throw away the remainder", so if you happen to use this for an even number (like 100, as in the original problem), you'll get 5000 rather than 5050.
It happens to work for their sample program because they used N=5 with the array [1, 2, 4]. Had they picked N=4 with [1, 2, 4], this program will say that the missing number is 1.
I didn't get any further in their list of questions.