File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -119,10 +119,12 @@ by `4` bits (`x << 4`).
119119#### Count Set Bits
120120
121121This method counts the number of set bits in a number using bitwise operators.
122+ The main idea is that we shift the number right by one bit at a time and check
123+ the result of ` & ` operation that is ` 1 ` if bit is set and ` 0 ` otherwise.
122124
123125``
124- Number: 5 = (0101) _ 2
125- Count Set Bits = 2
126+ Number: 5 = 0b0101
127+ Count of set bits = 2
126128``
127129
128130> See ` countSetBits ` function for further details.
Original file line number Diff line number Diff line change 11import countSetBits from '../countSetBits' ;
22
33describe ( 'countSetBits' , ( ) => {
4- it ( 'Should return number of set bits' , ( ) => {
5- expect ( countSetBits ( 5 ) ) . toBe ( 2 ) ;
6- expect ( countSetBits ( 1 ) ) . toBe ( 1 ) ;
7- } ) ;
4+ it ( 'should return number of set bits' , ( ) => {
5+ expect ( countSetBits ( 0 ) ) . toBe ( 0 ) ;
6+ expect ( countSetBits ( 1 ) ) . toBe ( 1 ) ;
7+ expect ( countSetBits ( 2 ) ) . toBe ( 1 ) ;
8+ expect ( countSetBits ( 3 ) ) . toBe ( 2 ) ;
9+ expect ( countSetBits ( 4 ) ) . toBe ( 1 ) ;
10+ expect ( countSetBits ( 5 ) ) . toBe ( 2 ) ;
11+ expect ( countSetBits ( 21 ) ) . toBe ( 3 ) ;
12+ expect ( countSetBits ( 255 ) ) . toBe ( 8 ) ;
13+ expect ( countSetBits ( 1023 ) ) . toBe ( 10 ) ;
14+ } ) ;
815} ) ;
Original file line number Diff line number Diff line change 11/**
2- * @param {number } number
2+ * @param {number } originalNumber
33 * @return {number }
44 */
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 ;
5+ export default function countSetBits ( originalNumber ) {
6+ let setBitsCount = 0 ;
7+ let number = originalNumber ;
8+
9+ while ( number ) {
10+ // Add last bit of the number to the sum of set bits.
11+ setBitsCount += number & 1 ;
12+
13+ // Shift number right by one bit to investigate other bits.
14+ number >>= 1 ;
1115 }
12- return count ;
16+
17+ return setBitsCount ;
1318}
You can’t perform that action at this time.
0 commit comments