Thursday, February 6, 2014

[twitter][*] Missing Number


You have n - 1 numbers from 1 to n. Your task is to find the missing number.

I.e.
n = 5
v = [4, 2, 5, 1]
The result is 3.
This is easy like sum them up and subtracted by (1+n)*n/2
My Code:
int findmissing(int a[], int n){
    int missing = 0;
    for(int i = 0; i < n; ++i){
        missing += a[i];
    }
    missing = (1+n+1)*(n+1)/2 - missing;
    return missing;
    }

No comments:

Post a Comment