File tree 3 files changed +32
-0
lines changed
3 files changed +32
-0
lines changed Original file line number Diff line number Diff line change @@ -116,6 +116,17 @@ by `4` bits (`x << 4`).
116
116
117
117
> See ` multiplyUnsigned ` function for further details.
118
118
119
+ #### Count Set Bits
120
+
121
+ This method counts the number of set bits in a number using bitwise operators.
122
+
123
+ ``
124
+ Number: 5 = (0101)_ 2
125
+ Count Set Bits = 2
126
+ ``
127
+
128
+ > See ` countSetBits ` function for further details.
129
+
119
130
## References
120
131
121
132
- [ Bit Manipulation on YouTube] ( https://www.youtube.com/watch?v=NLKQEOgBAnw&t=0s&index=28&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8 )
Original file line number Diff line number Diff line change
1
+ import countSetBits from '../countSetBits' ;
2
+
3
+ describe ( 'countSetBits' , ( ) => {
4
+ it ( 'Should return number of set bits' , ( ) => {
5
+ expect ( countSetBits ( 5 ) ) . toBe ( 2 ) ;
6
+ expect ( countSetBits ( 1 ) ) . toBe ( 1 ) ;
7
+ } ) ;
8
+ } ) ;
Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number } number
3
+ * @return {number }
4
+ */
5
+ export default function countSetBits ( number ) {
6
+ let count = 0 ;
7
+ let num = number ; // eslint error https://eslint.org/docs/rules/no-param-reassign
8
+ while ( num ) {
9
+ count += num & 1 ;
10
+ num >>= 1 ;
11
+ }
12
+ return count ;
13
+ }
You can’t perform that action at this time.
0 commit comments