Sum vs XOR

Sort by

recency

|

122 Discussions

|

  • + 0 comments

    C++:

    long sumXor(long n) {
        if (n == 0) {
            return 1;
        }
        
        int num_bits = std::floor(std::log2(n));
        int num_one_bits = __builtin_popcountl(n) - 1; // -1 excludes highest power of 2
        int num_zero_bits = num_bits - num_one_bits;
        
        // # of ways of choosing num_zero_bits
        return 1L << num_zero_bits; // pow(2, num_zero_bits)
    }
    
  • + 0 comments

    Python

    def sumXor(n):
        count = 1
        while n != 0:
            if n % 2 == 0:
                count *= 2
            n >>= 1
        return count
    
  • + 0 comments

    Medium story to show a Python solution @nemat-al/sum-vs-xor-hackerrank-python-e3438578934d">https://medium.com/@nemat-al/sum-vs-xor-hackerrank-python-e3438578934d

  • + 0 comments
    def sumXor(n):
        return 1 << list(bin(n or 1)[2:][::-1]).count('0')
    
  • + 0 comments

    C#:

    public static long sumXor(long n)
    {
        long mask = n | n >> 1;
        mask |= mask >> 2;
        mask |= mask >> 4;
        mask |= mask >> 8;
        mask |= mask >> 16;
        mask |= mask >> 32;
        return 1L << (int)long.PopCount(mask ^ n);
    }