Skip to content

Commit 8cefb8d

Browse files
committed
191. Number of 1 Bits
1 parent 47a2dd8 commit 8cefb8d

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@
255255
|198|[House Robber](https://leetcode.com/problems/house-robber/)| [js](./algorithms/houseRobber/Solution.js) |Easy|
256256
|197|[Rising Temperature](https://leetcode.com/problems/rising-temperature/)| [Mysql](./algorithms/risingTemperature/Solution.sql) |Easy|
257257
|196|[Delete Duplicate Emails](https://leetcode.com/problems/delete-duplicate-emails/)| [Mysql](./algorithms/deleteDuplicateEmails/Solution.sql) |Easy|
258-
|191|[Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/)| [java](./algorithms/numberof1bits/Solution.java) |Easy|
258+
|191|[Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/)| [java](./algorithms/numberof1bits/Solution.java), [js](./algorithms/numberof1bits/Solution.js) |Easy|
259259
|190|[Reverse Bits](https://leetcode.com/problems/reverse-bits/)| |Easy|
260260
|189|[Rotate Array](https://leetcode.com/problems/rotate-array/)| |Easy|
261261
|188|[Best Time to Buy and Sell Stock IV](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/)| |Hard|

algorithms/numberof1bits/Solution.js

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/**
2+
* @param {number} n - a positive integer
3+
* @return {number}
4+
*/
5+
var hammingWeight = function(n) {
6+
let result = 0
7+
// 二进制第一位是符号位,所以指需要循环后面31位
8+
for(let i = 0; i < 32; i++) {
9+
// (1 << i) 表示将数字1向左移动 i 位得到的值,即将二进制数1左移 i 位,得到一个只有第i位为1的二进制数
10+
// 运算符 & 用于将 n 的二进制表示和 (1 << i) 的二进制表示进行按位与运算。这将返回一个新的数字,其中只有当 n 的二进制表示中的第 i 位为1时,结果中的第 i 位才为1,否则为0
11+
// (n & (1 << i)) 这个表示 n 的二进制表示中的第 i 位是 0 还是 1
12+
if ((n & (1 << i)) !== 0) {
13+
result++
14+
}
15+
}
16+
return result
17+
};

0 commit comments

Comments
 (0)