diff options
author | Jack Sangdahl <[email protected]> | 2025-09-27 20:37:04 -0600 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2025-09-27 20:37:04 -0600 |
commit | 60f3439c8377ef8b99b5055b471840d53ab200a0 (patch) | |
tree | 1a8cc728f7932c3cc3f3debac5b180b1a7bef42e /hamming_distance.c | |
parent | 48f4961febc7d03056cd826682e4b3277c7b20ca (diff) | |
download | leetcode-60f3439c8377ef8b99b5055b471840d53ab200a0.tar.gz leetcode-60f3439c8377ef8b99b5055b471840d53ab200a0.zip |
461. hamming distance
Diffstat (limited to 'hamming_distance.c')
-rw-r--r-- | hamming_distance.c | 22 |
1 files changed, 22 insertions, 0 deletions
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 +} |