From 70b0e0a6527c2f0e170c85e4fa980626916ed981 Mon Sep 17 00:00:00 2001 From: Tapasweni Pathak Date: Mon, 27 Aug 2018 19:29:43 +0530 Subject: [PATCH] Add ifPowerOf2c (#155) --- src/algorithms/math/bits/README.md | 18 ++++++++++++++++++ .../math/bits/__test__/ifPowerOf2.test.js | 8 ++++++++ src/algorithms/math/bits/ifPowerOf2.js | 7 +++++++ 3 files changed, 33 insertions(+) create mode 100644 src/algorithms/math/bits/__test__/ifPowerOf2.test.js create mode 100644 src/algorithms/math/bits/ifPowerOf2.js diff --git a/src/algorithms/math/bits/README.md b/src/algorithms/math/bits/README.md index f4173af9..4c5c5148 100644 --- a/src/algorithms/math/bits/README.md +++ b/src/algorithms/math/bits/README.md @@ -91,6 +91,23 @@ inverting all of the bits of the number and adding 1 to it. > See [switchSign.js](switchSign.js) for further details. +#### Power of 2 + +This method checks if a number provided is power of two. It uses the property that when +a power of 2 is `&` with power of 2 minus 1, it would return 0 implying that the provided +number is power of 2. + +``` +Number: 4 +Power of 2: True + +Number: 1 +Power of 2: False +``` + +> See `ifPowerof2` function for further details. + + #### Multiply Two Numbers This method multiplies two integer numbers using bitwise operators. @@ -156,6 +173,7 @@ When we shift 1 four times it will become bigger than 5. > See [bitLength.js](bitLength.js) for further details. + ## References - [Bit Manipulation on YouTube](https://www.youtube.com/watch?v=NLKQEOgBAnw&t=0s&index=28&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8) diff --git a/src/algorithms/math/bits/__test__/ifPowerOf2.test.js b/src/algorithms/math/bits/__test__/ifPowerOf2.test.js new file mode 100644 index 00000000..564abc20 --- /dev/null +++ b/src/algorithms/math/bits/__test__/ifPowerOf2.test.js @@ -0,0 +1,8 @@ +import ifPowerOf2 from '../ifPowerOf2'; + +describe('ifPowerOf2', () => { + it('Should return if the number is power of 2 or not', () => { + expect(ifPowerOf2(5)).toBe(false); + expect(ifPowerOf2(4)).toBe(true); + }); +}); diff --git a/src/algorithms/math/bits/ifPowerOf2.js b/src/algorithms/math/bits/ifPowerOf2.js new file mode 100644 index 00000000..dd29f9f2 --- /dev/null +++ b/src/algorithms/math/bits/ifPowerOf2.js @@ -0,0 +1,7 @@ +/** + * @param {number} number + * @return bool + */ +export default function ifPowerOf2(number) { + return number && (!(number & (number - 1))); +}