Skip to content

Commit 3109aa1

Browse files
committed
hammingWeight
1 parent dc0069a commit 3109aa1

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
| 0160 | [getIntersectionNode](./code/0160_getIntersectionNode) || Linked List | 1️⃣✅ |
4646
| 0162 | [findPeakElement](./code/0162_findPeakElement) | ⭐⭐ | Array, Binary Search | |
4747
| 0189 | [rotate](./code/0189_rotate) | ⭐⭐ | Array | |
48+
| 0191 | [hammingWeight](./code/0191_hammingWeight) || Bit | 1️⃣ |
4849
| 0204 | [countPrimes](./code/0204_countPrimes) || Hash Table | |
4950
| 0206 | [reverseList](./code/0206_reverseList) || Linked List | |
5051
| 0222 | [countNodes](./code/0222_countNodes) | ⭐⭐ | Tree, Binary Search | |
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
/**
2+
* @param {number} n - a positive integer
3+
* @return {number}
4+
*/
5+
var hammingWeight = function (n) {
6+
let ans = 0;
7+
while (n) {
8+
n = n & (n - 1);
9+
ans++;
10+
}
11+
return ans;
12+
};
13+
14+
// 时间复杂度 O(logN)
15+
// 空间复杂度 O(1)

0 commit comments

Comments
 (0)