Sum vs XOR

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