mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-26 23:21:18 +08:00
Merge branch 'master' of https://github.com/trekhleb/javascript-algorithms into fourier
This commit is contained in:
commit
8ea35a5549
@ -143,6 +143,19 @@ Count of Bits to be Flipped: 1
|
|||||||
|
|
||||||
> See `bitsDiff` function for further details.
|
> See `bitsDiff` function for further details.
|
||||||
|
|
||||||
|
#### Count Bits of a Number
|
||||||
|
|
||||||
|
To calculate the number of valuable bits we need to shift `1` one bit left each
|
||||||
|
time and see if shifted number is bigger than the input number.
|
||||||
|
|
||||||
|
```
|
||||||
|
5 = 0b0101
|
||||||
|
Count of valuable bits is: 3
|
||||||
|
When we shift 1 four times it will become bigger than 5.
|
||||||
|
```
|
||||||
|
|
||||||
|
> See `bitsDiff` function for further details.
|
||||||
|
|
||||||
## References
|
## References
|
||||||
|
|
||||||
- [Bit Manipulation on YouTube](https://www.youtube.com/watch?v=NLKQEOgBAnw&t=0s&index=28&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8)
|
- [Bit Manipulation on YouTube](https://www.youtube.com/watch?v=NLKQEOgBAnw&t=0s&index=28&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8)
|
||||||
|
14
src/algorithms/math/bits/__test__/bitLength.test.js
Normal file
14
src/algorithms/math/bits/__test__/bitLength.test.js
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
import bitLength from '../bitLength';
|
||||||
|
|
||||||
|
describe('bitLength', () => {
|
||||||
|
it('should calculate number of bits that the number is consists of', () => {
|
||||||
|
expect(bitLength(0b0)).toBe(0);
|
||||||
|
expect(bitLength(0b1)).toBe(1);
|
||||||
|
expect(bitLength(0b01)).toBe(1);
|
||||||
|
expect(bitLength(0b101)).toBe(3);
|
||||||
|
expect(bitLength(0b0101)).toBe(3);
|
||||||
|
expect(bitLength(0b10101)).toBe(5);
|
||||||
|
expect(bitLength(0b11110101)).toBe(8);
|
||||||
|
expect(bitLength(0b00011110101)).toBe(8);
|
||||||
|
});
|
||||||
|
});
|
15
src/algorithms/math/bits/bitLength.js
Normal file
15
src/algorithms/math/bits/bitLength.js
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
/**
|
||||||
|
* Return the number of bits used in the binary representation of the number.
|
||||||
|
*
|
||||||
|
* @param {number} number
|
||||||
|
* @return {number}
|
||||||
|
*/
|
||||||
|
export default function bitLength(number) {
|
||||||
|
let bitsCounter = 0;
|
||||||
|
|
||||||
|
while ((1 << bitsCounter) <= number) {
|
||||||
|
bitsCounter += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return bitsCounter;
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user