From a5174ed199cacf163d29348c6dd439b91b764cf5 Mon Sep 17 00:00:00 2001 From: sarthakgupta1907-cell Date: Mon, 2 Nov 2026 14:14:37 +0530 Subject: [PATCH] fix: correct hammingDistance test case for (10, 14) --- Maths/HammingDistance.js | 25 +++++++++++++++++++++ Maths/test/HammingDistance.test.js | 36 ++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 Maths/HammingDistance.js create mode 100644 Maths/test/HammingDistance.test.js diff --git a/Maths/HammingDistance.js b/Maths/HammingDistance.js new file mode 100644 index 0000000000..001e7a203f --- /dev/null +++ b/Maths/HammingDistance.js @@ -0,0 +1,25 @@ +/** + * @function hammingDistance + * @description Hamming distance between two integers is the number of + * positions at which the corresponding bits are different. + * @param {number} a - First non-negative integer + * @param {number} b - Second non-negative integer + * @returns {number} - The Hamming distance between a and b + * @see https://en.wikipedia.org/wiki/Hamming_distance + * @example hammingDistance(1, 4) => 2 + * @example hammingDistance(3, 1) => 1 + */ +const hammingDistance = (a, b) => { + if (!Number.isInteger(a) || !Number.isInteger(b) || a < 0 || b < 0) { + throw new TypeError('Inputs must be non-negative integers') + } + let xor = a ^ b + let distance = 0 + while (xor > 0) { + distance += xor & 1 + xor >>= 1 + } + return distance +} + +export { hammingDistance } diff --git a/Maths/test/HammingDistance.test.js b/Maths/test/HammingDistance.test.js new file mode 100644 index 0000000000..ac1cc095cc --- /dev/null +++ b/Maths/test/HammingDistance.test.js @@ -0,0 +1,36 @@ +import { hammingDistance } from '../HammingDistance.js' + +describe('hammingDistance', () => { + test('hammingDistance(1, 4) returns 2', () => { + expect(hammingDistance(1, 4)).toBe(2) + }) + + test('hammingDistance(3, 1) returns 1', () => { + expect(hammingDistance(3, 1)).toBe(1) + }) + + test('hammingDistance(0, 0) returns 0', () => { + expect(hammingDistance(0, 0)).toBe(0) + }) + + test('hammingDistance(7, 0) returns 3', () => { + expect(hammingDistance(7, 0)).toBe(3) + }) + + // TO: + test('hammingDistance(10, 14) returns 1', () => { + expect(hammingDistance(10, 14)).toBe(1) + }) + + test('hammingDistance(same numbers) returns 0', () => { + expect(hammingDistance(5, 5)).toBe(0) + }) + + test('throws TypeError for negative input', () => { + expect(() => hammingDistance(-1, 4)).toThrow(TypeError) + }) + + test('throws TypeError for float input', () => { + expect(() => hammingDistance(1.5, 4)).toThrow(TypeError) + }) +})