Sort by

recency

|

245 Discussions

|

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

    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
    
  • + 0 comments

    Haskell

    module Main where
    
    import Data.Bits
    
    countZeroBits :: Integer -> Int
    countZeroBits n = go n 0
      where
        go :: Integer -> Int -> Int
        go 0 acc = acc
        go n acc = go (n `shiftR` 1) (acc + 1 - fromIntegral (n .&. 1))
    
    solve :: Integer -> Integer
    solve n = 1 `shiftL` countZeroBits n
    
    main :: IO ()
    main = readLn >>= print . solve
    
  • + 0 comments

    For every un-set bit , there are 2 posiiblities of a number that when added to the original number would give the same answer , if xored

    So , count the number of unset bits , and then raise it to the power of 2 , to get all combinations of numbers that when added to n will give the same result as to when xored by n

    def sumXor(n): # Write your code here ct = 0 while n: if n&1==0: ct+=1 n>>=1 return 2**ct

    `

  • + 0 comments
    long sumXor(long n) {
        long count = 0;
        long binary = n;
        while (binary > 0) {
            count += binary & 1 ? 0 : 1;
            binary >>= 1;
        }
        return 1L << count;
    }
    
    int main() {
        long n;
        scanf("%ld", &n);
    
        printf("%ld\n", sumXor(n));
    		
    		
    #Pratham Gupta
    		
    		
    		
    		
    
        return 0;
    }