diff --git a/Bit-Manipulation/ModuleOfPowerOfTwo.js b/Bit-Manipulation/ModuleOfPowerOfTwo.js new file mode 100644 index 0000000000..5d83c1571b --- /dev/null +++ b/Bit-Manipulation/ModuleOfPowerOfTwo.js @@ -0,0 +1,10 @@ +/** + * @author: gianvallejos92 + * This script will find the module of S % N using bitmask + * N is power of 2. E.g: 1, 2, 4, 8, 16, 32... + * Reference: https://www.geeksforgeeks.org/compute-modulus-division-by-a-power-of-2-number/ + */ + +export const ModuleOfPowerOfTwo = (s, n) => { + return (s & (n - 1)) +} diff --git a/Bit-Manipulation/test/ModuleOfPowerOfTwo.test.js b/Bit-Manipulation/test/ModuleOfPowerOfTwo.test.js new file mode 100644 index 0000000000..9502061afc --- /dev/null +++ b/Bit-Manipulation/test/ModuleOfPowerOfTwo.test.js @@ -0,0 +1,36 @@ +import { ModuleOfPowerOfTwo } from '../ModuleOfPowerOfTwo' + +test('Check 7 module 4', () => { + const res = ModuleOfPowerOfTwo(7, 4) + expect(res).toBe(3) +}) + +test('Check 150 module 4', () => { + const res = ModuleOfPowerOfTwo(150, 4) + expect(res).toBe(2) +}) + +test('Check 155 module 2', () => { + const res = ModuleOfPowerOfTwo(155, 2) + expect(res).toBe(1) +}) + +test('Check 150 module 16', () => { + const res = ModuleOfPowerOfTwo(150, 16) + expect(res).toBe(6) +}) + +test('Check 6 module 4', () => { + const res = ModuleOfPowerOfTwo(6, 4) + expect(res).toBe(2) +}) + +test('Check 12 module 8', () => { + const res = ModuleOfPowerOfTwo(12, 8) + expect(res).toBe(4) +}) + +test('Check 10 module 2', () => { + const res = ModuleOfPowerOfTwo(10, 2) + expect(res).toBe(0) +})