File tree Expand file tree Collapse file tree 3 files changed +37
-0
lines changed Expand file tree Collapse file tree 3 files changed +37
-0
lines changed Original file line number Diff line number Diff line change 222
222
- [ 309 Best Time to Buy and Sell Stock with Cooldown] ( https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/ )
223
223
- [ 322 Coin Change] ( https://leetcode.com/problems/coin-change/description/ )
224
224
- [ 337 House Robber III] ( https://leetcode.com/problems/house-robber-iii/description/ )
225
+ - [ 338 Counting Bits] ( https://leetcode.com/problems/counting-bits/description/ )
225
226
- [ 354 Russian Doll Envelopes] ( https://leetcode.com/problems/russian-doll-envelopes/description/ )
226
227
- [ 373 Find K Pairs with Smallest Sums] ( https://leetcode.com/problems/find-k-pairs-with-smallest-sums/description/ )
227
228
- [ 377 Combination Sum IV] ( https://leetcode.com/problems/combination-sum-iv/description/ )
Original file line number Diff line number Diff line change
1
+ from typing import List
2
+
3
+
4
+ class Solution :
5
+ """Base class for all LeetCode Problems."""
6
+
7
+ def countBits (self , n : int ) -> List [int ]:
8
+ """
9
+ Given an integer n, return an array ans of length n + 1 such that for each i
10
+ (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.
11
+ """
12
+ dp = [0 for _ in range (n + 1 )]
13
+ if n >= 1 :
14
+ dp [1 ] = 1
15
+ for i in range (2 , n + 1 ):
16
+ offset = i & (1 << (i .bit_length () - 1 )) - 1
17
+ dp [i ] = 1 + dp [offset ]
18
+ return dp
Original file line number Diff line number Diff line change
1
+ from typing import List
2
+
3
+ import pytest
4
+
5
+ from awesome_python_leetcode ._338_counting_bits import Solution
6
+
7
+
8
+ @pytest .mark .parametrize (
9
+ argnames = ["n" , "expected" ],
10
+ argvalues = [
11
+ (2 , [0 , 1 , 1 ]),
12
+ (5 , [0 , 1 , 1 , 2 , 1 , 2 ]),
13
+ ],
14
+ )
15
+ def test_func (n : int , expected : List [int ]):
16
+ """Tests the solution of a LeetCode problem."""
17
+ bits = Solution ().countBits (n )
18
+ assert bits == expected
You can’t perform that action at this time.
0 commit comments