File tree Expand file tree Collapse file tree 3 files changed +42
-0
lines changed
Expand file tree Collapse file tree 3 files changed +42
-0
lines changed Original file line number Diff line number Diff line change @@ -143,6 +143,19 @@ Count of Bits to be Flipped: 1
143143
144144> See ` bitsDiff ` function for further details.
145145
146+ #### Count Bits of a Number
147+
148+ To calculate the number of valuable bits we need to shift ` 1 ` one bit left each
149+ time and see if shifted number is bigger than the input number.
150+
151+ ```
152+ 5 = 0b0101
153+ Count of valuable bits is: 3
154+ When we shift 1 four times it will become bigger than 5.
155+ ```
156+
157+ > See ` bitsDiff ` function for further details.
158+
146159## References
147160
148161- [ 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 bitLength from '../bitLength' ;
2+
3+ describe ( 'bitLength' , ( ) => {
4+ it ( 'should calculate number of bits that the number is consists of' , ( ) => {
5+ expect ( bitLength ( 0b0 ) ) . toBe ( 0 ) ;
6+ expect ( bitLength ( 0b1 ) ) . toBe ( 1 ) ;
7+ expect ( bitLength ( 0b01 ) ) . toBe ( 1 ) ;
8+ expect ( bitLength ( 0b101 ) ) . toBe ( 3 ) ;
9+ expect ( bitLength ( 0b0101 ) ) . toBe ( 3 ) ;
10+ expect ( bitLength ( 0b10101 ) ) . toBe ( 5 ) ;
11+ expect ( bitLength ( 0b11110101 ) ) . toBe ( 8 ) ;
12+ expect ( bitLength ( 0b00011110101 ) ) . toBe ( 8 ) ;
13+ } ) ;
14+ } ) ;
Original file line number Diff line number Diff line change 1+ /**
2+ * Return the number of bits used in the binary representation of the number.
3+ *
4+ * @param {number } number
5+ * @return {number }
6+ */
7+ export default function bitLength ( number ) {
8+ let bitsCounter = 0 ;
9+
10+ while ( ( 1 << bitsCounter ) <= number ) {
11+ bitsCounter += 1 ;
12+ }
13+
14+ return bitsCounter ;
15+ }
You can’t perform that action at this time.
0 commit comments