Sum vs XOR

  • + 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)
    }