sundeepblue
4/12/2014 - 4:35 PM

find one missing number from 1 to N.

find one missing number from 1 to N.

// solution 1, get sum, then substract each
int find_missing(vector<int>& A, int N) {
    // use long long to avoid overflow.
    // the maximum signed long long number is x = 9223372036854775807 (2^63-1)
    // the sum of all int, from 0 to 2^31-1 is y = 2305843008139952128
    // x is still larger than y because x/y = 4.000000001862645.
    // thus, it is safe to use "long long" to hold all sum.
    long long sum = 0;
    for(int i=1; i<=N; ++i) sum += i;
    for(int i : A) sum -= i;
    return (int)sum;
}

// solution 2, better, use XOR
int find_missing(vector<int>& A, int N) {
    int x = A[0];
    for(int i=1; i<A.size(); ++i) 
        x ^= A[i];
    int y = 1;
    for(int i=2; i<= N; ++i) 
        y ^= i;
    return x ^ y;
}