Day 6

Photo by Dominik Scythe on Unsplash

The Problem

Write an algorithm that finds the total number of set bits in all integers between 1 and N


My Solution

Today I decided that I would switch up my coding problem language and give python a try. Unfortunately, the syntax highlighter that is used does not have python as an option, but feel free to view the code using the button below.

# Helper method to convert a number to binary
def convertToBinary(num):
	return str(bin(num))[2:]

# The main method
def bits(n):
	if n == 0:
		return 0
		binary = convertToBinary(n)
		count = binary.count('1')
		return count + bits(n - 1)

# Should return 4

# Should return 2222


Leave a Reply

Your email address will not be published. Required fields are marked *