Skip to content

Commit 9111568

Browse files
committedAug 13, 2018
Add bits counter function.
1 parent 3c37ba4 commit 9111568

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed
 

‎src/algorithms/math/bits/README.md

+13
Original file line numberDiff line numberDiff 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 numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
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+
});

‎src/algorithms/math/bits/bitLength.js

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
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+
}

0 commit comments

Comments
 (0)
Please sign in to comment.