Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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
Lines changed: 41 additions & 0 deletions
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+
def countBits(self, n):
17+
ans = []
18+
for i in range(n+1):
19+
cur = 0
20+
while i:
21+
cur += i & 1
22+
i >>= 1
23+
ans.append(cur)
24+
return ans
25+
26+
# T:O(NlogN)
27+
# S:O(N)
28+
29+
#DP way
30+
def countBits(self, n):
31+
dp = [0]*(n+1)
32+
offset = 0
33+
34+
for i in range(1,n+1):
35+
if offset*2 == i:
36+
offset = i
37+
dp[i] = 1 + dp[i-offset]
38+
return dp
39+
40+
# T:O(N)
41+
# S:O(N)

‎README.md

Lines changed: 1 addition & 0 deletions
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)

AltStyle によって変換されたページ (->オリジナル) /