Skip to content

Commit a5174ed

Browse files
fix: correct hammingDistance test case for (10, 14)
1 parent 5c39e87 commit a5174ed

2 files changed

Lines changed: 61 additions & 0 deletions

File tree

‎Maths/HammingDistance.js‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* @function hammingDistance
3+
* @description Hamming distance between two integers is the number of
4+
* positions at which the corresponding bits are different.
5+
* @param {number} a - First non-negative integer
6+
* @param {number} b - Second non-negative integer
7+
* @returns {number} - The Hamming distance between a and b
8+
* @see https://en.wikipedia.org/wiki/Hamming_distance
9+
* @example hammingDistance(1, 4) => 2
10+
* @example hammingDistance(3, 1) => 1
11+
*/
12+
const hammingDistance = (a, b) => {
13+
if (!Number.isInteger(a) || !Number.isInteger(b) || a < 0 || b < 0) {
14+
throw new TypeError('Inputs must be non-negative integers')
15+
}
16+
let xor = a ^ b
17+
let distance = 0
18+
while (xor > 0) {
19+
distance += xor & 1
20+
xor >>= 1
21+
}
22+
return distance
23+
}
24+
25+
export { hammingDistance }

‎Maths/test/HammingDistance.test.js‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { hammingDistance } from '../HammingDistance.js'
2+
3+
describe('hammingDistance', () => {
4+
test('hammingDistance(1, 4) returns 2', () => {
5+
expect(hammingDistance(1, 4)).toBe(2)
6+
})
7+
8+
test('hammingDistance(3, 1) returns 1', () => {
9+
expect(hammingDistance(3, 1)).toBe(1)
10+
})
11+
12+
test('hammingDistance(0, 0) returns 0', () => {
13+
expect(hammingDistance(0, 0)).toBe(0)
14+
})
15+
16+
test('hammingDistance(7, 0) returns 3', () => {
17+
expect(hammingDistance(7, 0)).toBe(3)
18+
})
19+
20+
// TO:
21+
test('hammingDistance(10, 14) returns 1', () => {
22+
expect(hammingDistance(10, 14)).toBe(1)
23+
})
24+
25+
test('hammingDistance(same numbers) returns 0', () => {
26+
expect(hammingDistance(5, 5)).toBe(0)
27+
})
28+
29+
test('throws TypeError for negative input', () => {
30+
expect(() => hammingDistance(-1, 4)).toThrow(TypeError)
31+
})
32+
33+
test('throws TypeError for float input', () => {
34+
expect(() => hammingDistance(1.5, 4)).toThrow(TypeError)
35+
})
36+
})

0 commit comments

Comments
 (0)