From 60f3439c8377ef8b99b5055b471840d53ab200a0 Mon Sep 17 00:00:00 2001 From: Jack Sangdahl Date: Sat, 27 Sep 2025 20:37:04 -0600 Subject: 461. hamming distance --- hamming_distance.c | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 hamming_distance.c (limited to 'hamming_distance.c') diff --git a/hamming_distance.c b/hamming_distance.c new file mode 100644 index 0000000..625f178 --- /dev/null +++ b/hamming_distance.c @@ -0,0 +1,22 @@ +// 461. Hamming Distance +#include "leetcode.h" + +/* + * the hamming distance between two integers is the number of positions at which + * the corresponding bits are different. given two integers 'x' and 'y', return + * the hamming distance between them. + */ + +int hammingDistance(int x, int y) { + int ans = 0, n = x ^ y; + while (n) { + ++ans; + n &= n - 1; + } + return ans; +} + +int main() { + printf("%d\n", hammingDistance(1, 4)); // expect: 2 + printf("%d\n", hammingDistance(3, 1)); // expect: 1 +} -- cgit v1.2.3