Write an algorithm to find F(n) the number of bits set to 1, in all numbers from 1 to n for any given value of n.
F(n)
Complexity should be O(log n)
O(log n)
Here is my solution to this. Time complexity : O (Log n)
public int countSetBits(int n){ int count=0; while(n>0){ int i= (int)(Math.log10(n)/Math.log10(2)); count+= Math.pow(2, i-1)*i; count+= n-Math.pow(2, i)+1; n-= Math.pow(2, i); } return count; }