Skip to content

Commit aa804e3

Browse files
committed
Find the sum of number of set bits in a range of numbers
1 parent 0b53753 commit aa804e3

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ This directory contains various types of algorithm questions like Dynamic Progra
3535
4. [Math](algorithms/math)
3636
5. [Misc](algorithms/miscellaneous)
3737
6. [Sorting](algorithms/sorting)
38+
7. [Bit Manipulation](algorithms/bit_manipulation)
3839

3940
### Bookmarks
4041

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Question: Find the sum of number of set bits in all the numbers in the range [1, n].
2+
3+
def countBits(n):
4+
5+
""" Consider a number x and half of the number (x//2).
6+
The binary representation of x has all the digits as
7+
the binary representation of x//2 followed by an additional
8+
digit at the last position. Therefore, we can find the number
9+
of set bits in x by finding the number of set bits in x//2
10+
and determining whether the last digit in x is 0 or 1. """
11+
12+
res = [0] * (n+1)
13+
for i in range(1, n+1):
14+
res[i] = res[i//2] + (i & 1)
15+
return sum(res)
16+
17+
18+
# Extension: Find the sum of number of set bits in all the numbers in the range [m, n].
19+
# Answer: In countBits(m, n), return sum(res) - sum(res[:m])

0 commit comments

Comments
 (0)