Skip to content

Commit a114c48

Browse files
Counting Bits
1 parent e5e12e3 commit a114c48

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed
+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
'''Leetcode- https://leetcode.com/problems/counting-bits/ '''
2+
'''
3+
Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.
4+
5+
Example 1:
6+
7+
Input: n = 2
8+
Output: [0,1,1]
9+
Explanation:
10+
0 --> 0
11+
1 --> 1
12+
2 --> 10
13+
'''
14+
15+
# Bit manipulation approach
16+
defcountBits(self, n):
17+
ans= []
18+
foriinrange(n+1):
19+
cur=0
20+
whilei:
21+
cur+=i&1
22+
i>>=1
23+
ans.append(cur)
24+
returnans
25+
26+
# T:O(NlogN)
27+
# S:O(N)
28+
29+
#DP way
30+
defcountBits(self, n):
31+
dp= [0]*(n+1)
32+
offset=0
33+
34+
foriinrange(1,n+1):
35+
ifoffset*2==i:
36+
offset=i
37+
dp[i] =1+dp[i-offset]
38+
returndp
39+
40+
# T:O(N)
41+
# S:O(N)

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,5 @@ Check the notes for the explaination - [Notes](https://stingy-shallot-4ea.notion
2626
-[x][Climbing Stairs](Dynamic-Programming/70-Climbing-Stairs.py)
2727
-[x][Maximum Subarray](Dynamic-Programming/53-maximum-subarray.py)
2828
-[x][Range Sum Query - Immutable](Dynamic-Programming/303-Range-Sum-Query-Immutable.py)
29+
-[x][Counting Bits](Dynamic-Programming/338-Counting-Bits.py)
2930

0 commit comments

Comments
 (0)
close