• + 0 comments

    If you use the easy to code approach where you check every number, you can get the correct answer for small numbers. If you understand bits you'll be able to see that the correct answer is the invert of the original number. EX: 10 (0000 1010) - Answer: 5 (0000 0101) So what you can do is invert the bits until you reach the leftmost bit value on the original. C#:

    public static long theGreatXor(long x)
        {
            long result = 0;
            int i = 0;
            while(x > 1)
            {
                if((x & 1) == 0)
                {
                    result ^= (long)1 << i;
                }
                x >>= 1;
                i++;
            }
            
            return result;
        }