human
Count total set bits in all numbers from 1 to n | Function which counts set bits from 0 to n.
ans store sum of set bits from 0 to n.
while n greater than equal to 2 ^ i.
This k will get flipped after 2 ^ i iterations.
change is iterator from 2 ^ i to 1.
This will loop from 0 to n for every bit position.
When change = 1 flip the bit.
again set change to 2 ^ i.
increment the position.
Driver code"
Solution in Python:
assistant
#Here is code to count total set bits in all numbers from 1 to n and the other steps required.
 def countSetBits ( n ) :
	i = 0
	ans = 0
	while ( ( 1 << i ) <= n ) :
		k = 0
		change = 1 << i
		for j in range ( 0 , n + 1 ) :
			ans += k
			if change == 1 :
				k = not k
				change = 1 << i
			else :
				change -= 1
		i += 1
	return ans
if __name__ == " _ _ main _ _ " :
	n = 17
	print ( countSetBits ( n ) )