File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /**
2+ * @param {number } n
3+ * @return {number }
4+ */
5+
6+ // 31 비트 범위는 상수로 취급
7+
8+ // Log-based calculation
9+ // TC: O(1) / SC: O(1)
10+ // 비트 제약이 없을 경우 -> TC: O(logn) / SC: O(logn)
11+ var hammingWeight = function ( n ) {
12+ const BIT_RANGE = 31 ;
13+ let bits = Array . from ( { length : BIT_RANGE } ) . fill ( 0 ) ;
14+
15+ let remainder = n ;
16+ while ( remainder > 0 ) {
17+ const exp = Math . min ( Math . floor ( Math . log2 ( remainder ) ) , BIT_RANGE - 1 ) ;
18+ bits [ exp ] = true ;
19+ const value = remainder <= 1 ? 1 : Math . pow ( 2 , exp ) ;
20+ remainder -= value ;
21+ }
22+
23+ return bits . filter ( value => value ) . length ;
24+ } ;
25+
26+ // Log-based calculation without an array
27+ // TC: O(1) / SC: O(1)
28+ // 비트 제약이 없을 경우 -> TC: O(logn) / SC: O(1)
29+ var hammingWeight = function ( n ) {
30+ const BIT_RANGE = 31 ;
31+ let bitCount = 0 ;
32+
33+ let remainder = n ;
34+ while ( remainder > 0 ) {
35+ const exp = Math . min ( Math . floor ( Math . log2 ( remainder ) ) , BIT_RANGE - 1 ) ;
36+ const value = remainder <= 1 ? 1 : Math . pow ( 2 , exp ) ;
37+ remainder -= value ;
38+ bitCount ++ ;
39+ }
40+
41+ return bitCount ;
42+ } ;
43+
44+ // Converting binary string with the JS feature
45+ // TC: O(1) / SC: O(1)
46+ // 비트 제약이 없을 경우 -> TC: O(logn) / SC: O(logn)
47+ var hammingWeight = function ( n ) {
48+ const binaryString = n . toString ( 2 ) ;
49+ return [ ...binaryString ] . filter ( v => v === '1' ) . length ;
50+ } ;
51+
52+ // Bit manipulation
53+ // TC: O(1) / SC: O(1)
54+ // 비트 제약이 없을 경우 -> TC: O(logn) / SC: O(logn)
55+ var hammingWeight = function ( n ) {
56+ let count = 0 ;
57+
58+ while ( n > 0 ) {
59+ n = n & ( n - 1 ) ;
60+ count ++ ;
61+ }
62+
63+ return count ;
64+ } ;
You can’t perform that action at this time.
0 commit comments