aboutsummaryrefslogtreecommitdiff
path: root/hamming_distance.c
diff options
context:
space:
mode:
Diffstat (limited to 'hamming_distance.c')
-rw-r--r--hamming_distance.c22
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
+}