Skip to content

Commit b663600

Browse files
committed
solve: number of 1 bits
1 parent 1c5fdaf commit b663600

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

number-of-1-bits/evan.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* @param {number} n, maximum 32 bit number
3+
* @return {number}
4+
*/
5+
var hammingWeight = function (n) {
6+
return n.toString(2).replace(/0/g, "").length;
7+
};
8+
9+
/**
10+
* Time Complexity: O(1)
11+
* Reason:
12+
* - n.toString(2): Converts the number to a binary string, which has a fixed length of up to 32 bits. This is O(1) because the length is constant.
13+
* - replace(/0/g, ''): Removes all '0's from the binary string. The operation is O(1) since the string length is at most 32 characters.
14+
* - .length: Getting the length of the resulting string is O(1).
15+
* Therefore, the overall time complexity is O(1).
16+
*
17+
* Space Complexity: O(1)
18+
* Reason:
19+
* - n.toString(2): The binary string representation has a fixed maximum length of 32 characters, which requires O(1) space.
20+
* - replace(/0/g, ''): The resulting string after removing '0's has a length of at most 32 characters, so it also requires O(1) space.
21+
* - .length: Retrieving the length of a string does not require additional space.
22+
* Therefore, the overall space complexity is O(1).
23+
*/

0 commit comments

Comments
 (0)