diff --git a/Bit-Manipulation/MinMaxElement.js b/Bit-Manipulation/MinMaxElement.js new file mode 100644 index 0000000000..54277128a2 --- /dev/null +++ b/Bit-Manipulation/MinMaxElement.js @@ -0,0 +1,17 @@ +/** + * @author : nikgautamgithub + * + * Find max or min element using bit operators. + * @param {number} x - The input number to compare. + * @param {number} y - The input number to compare. + * @returns Min/Max Element + * + * @example + * const maxi = max(5,3) // Returns max number i.e. 5 + * const mini = min(5,3); // Returns min number i.e. 3 + */ +const max = (x, y) => x ^ ((x ^ y) & -(x < y ? 1 : 0)) + +const min = (x, y) => y ^ ((x ^ y) & -(x < y ? 1 : 0)) + +export { min, max } diff --git a/Bit-Manipulation/test/MinMaxElement.test.js b/Bit-Manipulation/test/MinMaxElement.test.js new file mode 100644 index 0000000000..8a45d779d3 --- /dev/null +++ b/Bit-Manipulation/test/MinMaxElement.test.js @@ -0,0 +1,9 @@ +import { min, max } from '../minMaxElement' + +test('Find max element from 5 and 3 :', () => { + expect(max(5, 3)).toBe(5) +}) + +test('Find min element from 5 and 3 :', () => { + expect(min(5, 3)).toBe(3) +})