File tree Expand file tree Collapse file tree 1 file changed +23
-0
lines changed Expand file tree Collapse file tree 1 file changed +23
-0
lines changed Original file line number Diff line number Diff line change 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+ */
You can’t perform that action at this time.
0 commit comments