Sort by

recency

|

248 Discussions

|

  • + 0 comments

    sum is essentially xor except, there's the possibility of a carry with addition: 1 ^ 1 == 0, while 1 + 1 = 10. That's why you want to count the number of zeroes in the input. Once you have that, you need all the permutations of toggling those zeroes, which is 2 ** n_zeroes, or 1 << n_zeroes.

    If we choose 100, which is b'110 0100, there are four zeroes, so there are 16 ways to toggle the zeroes -> 0, 1, 10, 11, 1000, 1001, 1010, 1011, 10000, 10001, 10010, 10011, 11000, 11001, 11010, 11011.

  • + 1 comment

    Here is my Python solution! A really clever trick is to realize that the amount is just 2 raised to the amount of 0s in the binary representation of the number.

    def sumXor(n):
        if n == 0:
            return 1
        return 2 ** (bin(n).count("0") - 1)
    
  • + 0 comments

    Here is my C++ solution, you can watch the explanation here : https://youtu.be/yj0yNv6BZa8

    long sumXor(long n) {
        long result = 1;
        while(n) {
            result *= (n % 2) ? 1 : 2;
            n /= 2;
        }
        return result;
    }
    
  • + 0 comments

    C solution

    long sumXor (long n) {
        long result = 0;
        while(n) {
            if(!(n & 0x1)) {
                result++;
            }
            n = n>>0x1;
        }
        return 0x1ULL << (result);
    }
    
  • + 0 comments

    More at https://github.com/pakbungdesu/hackerrank-problem-solving.git

    Java

    public static long sumXor(long n) {
        if (n == 0) {
            return 1;
        } else {
            String bin = Long.toBinaryString(n);
            int zero_bits = bin.length() - bin.replace("0", "").length();
            return (long)Math.pow(2, zero_bits);
        }
    }
    

    Pyhon

    def sumXor(n):
        if n == 0:
            return 1
        else:
            zero_bits = bin(n)[2:].count('0')  # Ignore the '0b' prefix
            return 2**zero_bits