You are given a number N. Find the total number of setbits in the numbers from 1 to N.
Time : O(lgn)
Space : O(1)
1 2 3 4 5 6 7 8 9
classSolution{ public: intcountBits(int n){ if(n <= 1) return n; int lg = log2(n); int res = lg * (1<<(lg-1)) + n - (1<<lg) + 1; return res + countBits(n ^ (1<<lg)); } };