題目出處
難度
easy
個人範例程式碼
class Solution:
def hammingWeight(self, n: int) -> int:
# 7 (10) = 111 (2)
# 4 (10) = 100 (2)
# 3 (10) = 011 (2)
cnt = 0
while(n != 0):
cnt += (n & 1) # and first bit
n = n >> 1 # (// 2)
return cnt
算法說明
簡單的位元運算題目,
我們可以先觀察「 10進位 (10) 與 2進位 (2) 」的變化,
7 (10) = 111 (2)
4 (10) = 100(2)
3 (10) = 11(2)
我們提取第一個位元 (最右側位元) 的方式是 (原數字 & 1),
並一路往右 >> 1,直到原值只剩下 0。
input handling
x
Boundary conditions
用 while 至 0 來控制範圍。
Reference
⭐ Leetcode 解題紀錄 ⭐ | 題型 | 資料結構 | Python Solution | C++ Solution | Note | |
---|---|---|---|---|---|---|
⭐BFS 相關題型 ⭐ | ||||||
104 | Maximum Depth of Binary Tree | BFS (分層) | Python | |||
94 | Binary Tree Inorder Traversal | BFS (分層) | Tree | Python | 內含 處理 Tree 樹問題的重點 | |
102 | Binary Tree Level Order Traversal | BFS (分層) | Tree | Python | ||
103 | Binary Tree Zigzag Level Order Traversal | BFS (分層) | Tree | Python | ||
107 | Binary Tree Level Order Traversal II | BFS (分層) | Tree | Python | ||
133 | Clone Graph | BFS (分層) | Graph | Python | Graph 的基本操作 #重要題型 | |
127 | Word Ladder | BFS (分層), DFS | Graph | Python | ||
[Lint] 127 | Topological Sorting | BFS (拓撲) | Python | 內有 indegree, outdegree 介紹 #重要題型 | ||
207 | Course Schedule | BFS (拓樸) | Graph | Python | ||
210 | Course Schedule II | BFS (拓樸) | Graph | Python | ||
[Lint] 892 | Alien Dictionary | BFS (拓樸) | Graph | Python | ||
[Lint] 431 | Connected Component in Undirected Graph | BFS (連通塊) | Graph | Python | 內含 BFS 模板 #重要題型 | |
1091 | Shortest Path in Binary Matrix | BFS (最短路徑) | Matrix | Python | ||
⭐ Binary Serach 相關題型 ⭐ | ||||||
33 | Search in Rotated Sorted Array | Binary Serach | Array | Python | #重要題型 | |
34 | Find First and Last Position of Element in Sorted Array | Binary Serach | Python | |||