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 bf8fe89

Browse files
D. J.:
- Added the leetcode problem and solution for 338
1 parent 3abfbb7 commit bf8fe89

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,7 @@
222222
- [309 Best Time to Buy and Sell Stock with Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/)
223223
- [322 Coin Change](https://leetcode.com/problems/coin-change/description/)
224224
- [337 House Robber III](https://leetcode.com/problems/house-robber-iii/description/)
225+
- [338 Counting Bits](https://leetcode.com/problems/counting-bits/description/)
225226
- [354 Russian Doll Envelopes](https://leetcode.com/problems/russian-doll-envelopes/description/)
226227
- [373 Find K Pairs with Smallest Sums](https://leetcode.com/problems/find-k-pairs-with-smallest-sums/description/)
227228
- [377 Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/description/)
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
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

‎tests/test_338_counting_bits.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
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

0 commit comments

Comments
(0)

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