Sum vs XOR

Sort by

recency

|

125 Discussions

|

  • + 0 comments

    java

        public static long sumXor(long n) {
            // Write your code here
            if(n == 0) return 1 ;
            
            int totalOneBits = Long.bitCount(n) ;
            int totalBits = Long.toBinaryString(n).length() ;
             int zeroBits = totalBits - totalOneBits ;
             
             return 1l << zeroBits ; //bitwise left shift => 8 4 2 1 ;power of 2
        }
    
  • + 0 comments

    Java

    I have no idea how to make it faster ,..

    public static long sumXor(long n) {
            List<Long> xorsList = new ArrayList<>();
            xorsList.add(0l);
            for(int i=0;i<64;i++){
                long powerOfTwo = (long)Math.pow(2, i);
                if(powerOfTwo>n)
                    break;
                if((powerOfTwo+n)==(powerOfTwo^n)){
                    xorsList.add(powerOfTwo);
                }
            }
            if(xorsList.size()==1)
                return xorsList.size();
            Set<Long> resultList = new HashSet<>(xorsList);
            resultList = scrambleXORS(xorsList,resultList,n,xorsList.get(0),0);
            return resultList.size();
        }
        public static Set<Long> scrambleXORS(List<Long> baseXORS,Set<Long> resultList,
                                              long n, long currNumber,int index) {
            if(index>=baseXORS.size()){
                resultList.add(currNumber);
                return resultList;
            }
            for(int i=index;i<baseXORS.size();i++)
            {
                Long xorBase = baseXORS.get(i);
                long currSum = currNumber+xorBase;
                resultList.add(currSum);
                if(currSum<n)
                {
                    scrambleXORS(baseXORS,resultList,n,currSum, i+1);
                }
            }
            return resultList;
        }
    
  • + 0 comments

    my rust approach:

    fn sumXor(n: i64) -> i64 {
        2i64.pow(n.count_zeros() - n.leading_zeros())
    }
    
  • + 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