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 e72a75d

Browse files
🐱(dynamic): 338. 比特位计数
补充解法二
1 parent 1614d48 commit e72a75d

File tree

1 file changed

+44
-2
lines changed

1 file changed

+44
-2
lines changed

‎docs/algorithm/dynamic/README.md‎

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1316,12 +1316,11 @@ class Solution(object):
13161316
return res[amount]
13171317
```
13181318

1319-
13201319
## 338. 比特位计数
13211320

13221321
[原题链接](https://leetcode-cn.com/problems/counting-bits/description/)
13231322

1324-
### 思路
1323+
### 解法一
13251324

13261325
动态规划无疑了
13271326

@@ -1349,6 +1348,49 @@ class Solution(object):
13491348
return List1[:num+1]
13501349
```
13511350

1351+
### 解法二
1352+
1353+
奇偶数的二进制规律:
1354+
1355+
- 奇数二进制数总比前一个偶数二进制数多 1 个 1(即最后 1 位)
1356+
- 偶数二进制数 `x` 中 1 的个数总等于 `x / 2` 中 1 的个数(除 2 等于右移 1 位,即抹去最后一位 0)
1357+
1358+
<!-- tabs:start -->
1359+
1360+
c
1361+
1362+
```python
1363+
class Solution:
1364+
def countBits(self, num: int) -> List[int]:
1365+
ans = [0 for _ in range(num + 1)]
1366+
for i in range(num + 1):
1367+
if i % 2 == 0:
1368+
# 偶数
1369+
ans[i] = ans[i // 2]
1370+
else:
1371+
# 奇数
1372+
ans[i] = ans[i - 1] + 1
1373+
return ans
1374+
```
1375+
1376+
#### **Go**
1377+
1378+
```go
1379+
func countBits(num int) []int {
1380+
ans := make([]int, num + 1)
1381+
for i := 0; i <= num; i++ {
1382+
if i % 2 == 0 {
1383+
ans[i] = ans[i / 2]
1384+
} else {
1385+
ans[i] = ans[i - 1] + 1
1386+
}
1387+
}
1388+
return ans
1389+
}
1390+
```
1391+
1392+
<!-- tabs:end -->
1393+
13521394
## 714. 买卖股票的最佳时机含手续费
13531395

13541396
[原题链接](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/)

0 commit comments

Comments
(0)

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