Saturday, December 7, 2013

Sum of two's complement of n integers

I saw a sum of two's complement puzzle on some site and started doing it I was able to do solve the problem but couldn't able to finish below 5 sec, then i came up with the above generating function helps me to solve in less time.  Below is a sample code in Java


public static class SumOfTwosComplement{
        int bitPositionCount=2;
        long bitPositionDiff=1;
        int diffIncrement=1;
        long occurence=1;
        int positionCount;
      
        public long calculate(int i){
            if(i==0){
                positionCount=0;
                return 0;
            }else if(i==1){
                positionCount=1;
                return 1;
            }
              
          
            for(;bitPositionCount<=i && bitPositionCount >=0;){
                occurence+=bitPositionDiff;
                bitPositionDiff=2*bitPositionDiff+diffIncrement;
              
                diffIncrement=2*diffIncrement;
              
                positionCount=bitPositionCount;
                bitPositionCount=bitPositionCount*2;
              
            }
            return occurence;
        }
    }