Given numbers from 1 to 2^32-1, one is missing. How to find the missing number optimally?

前端 未结 5 1026
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-14 03:58

You are given 2^32-2 unique numbers that range from 1 to 2^32-1. It\'s impossible to fit all the numbers into memory (thus sorting is not an option). You are asked to find t

5条回答
  •  时光说笑
    2020-12-14 05:04

    Major Edit: Trust me to make things much harder than they have to be.

    XOR all of them.

    I'm assuming here that the numbers are 1 to 232 - 1 inclusive. This should use 1 extra memory location of 32 bits.

    EDIT: I thought I could get away with magic. Ah well.

    Explanation:

    For those who know how Hamming Codes work, it's the same idea.

    Basically, for all numbers from 0 to 2n - 1, there are exactly 2(n - 1) 1s in each bit position of the number. Therefore xoring all those numbers should actually give 0. However, since one number is missing, that particular column will give one, because there's an odd number of ones in that bit position.

    Note: Although I personally prefer the ** operator for exponentiation, I've changed mine to ^ because that's what the OP has used. Don't confuse ^ for xor.

提交回复
热议问题