File tree 2 files changed +20
-0
lines changed
algorithms/bit_manipulation
2 files changed +20
-0
lines changed Original file line number Diff line number Diff line change @@ -35,6 +35,7 @@ This directory contains various types of algorithm questions like Dynamic Progra
35
35
4 . [ Math] ( algorithms/math )
36
36
5 . [ Misc] ( algorithms/miscellaneous )
37
37
6 . [ Sorting] ( algorithms/sorting )
38
+ 7 . [ Bit Manipulation] ( algorithms/bit_manipulation )
38
39
39
40
### Bookmarks
40
41
Original file line number Diff line number Diff line change
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])
You can’t perform that action at this time.
0 commit comments