Constant time and constant space, both O(1)


#1
int MOD=pow(10,9)+7;

int Solution::solve(int A) {
    if(A==0) return 0;
    long long cnt=0;
    for(long long i=31;i>=0;--i){
        if(1<<i&A)
        {
            // cnt+=(A&(~(1<<index)+1);
            A=(A&(~(1<<i)));
            cnt+=i*(1<<(i-1))+A+1;
            cnt%=MOD;
        }
    }
    
    for(long long i=31;i>=0;--i){
        if(1<<i&A)
        {
            // cnt+=(A&(~(1<<index)+1);
            A=(A&(~(1<<i)));
            cnt+=A+1;
            cnt%=MOD;
        }
    }
    return (int)cnt;
}

If anyone is interested in knowing how this works, please let me know.


#2

I will surely like to know how it is working. Please explain the algorithm.


#3

Hey, the algorithm is simple but it will need a detailed explanation. I would like to know if it is okay if I post the description in some time? By sometime I mean by tomorrow or day after tomorrow.