aboutsummaryrefslogtreecommitdiff
path: root/number_complement.c
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2024-08-21 18:52:54 -0600
committerJack Sangdahl <[email protected]>2024-08-21 18:52:54 -0600
commit77f46021e62b1d16803e746db4a39d22d17700e2 (patch)
tree93831ef8dce8c9988391ad0c10b7673b52640fd9 /number_complement.c
parent716c5f21d28b5fb06efd5cd637ae14056d1eead8 (diff)
downloadleetcode-77f46021e62b1d16803e746db4a39d22d17700e2.tar.gz
leetcode-77f46021e62b1d16803e746db4a39d22d17700e2.zip
476. number complement
Diffstat (limited to 'number_complement.c')
-rw-r--r--number_complement.c16
1 files changed, 16 insertions, 0 deletions
diff --git a/number_complement.c b/number_complement.c
new file mode 100644
index 0000000..297f22f
--- /dev/null
+++ b/number_complement.c
@@ -0,0 +1,16 @@
+// 476. Number Complement
+#include "leetcode.h"
+
+/*
+ * the complement of an integer is the integer you get when you flip all the 0's
+ * to 1's and all the 1's to 0's in its binary representation. for example, the
+ * integer 5 is "101" in binary and its complement is "010", which is the
+ * integer 2. given an integer 'num', return its complement
+ */
+
+int findComplement(int num) { return (uint)~0 >> __builtin_clz(num) ^ num; }
+
+int main() {
+ printf("%d\n", findComplement(5)); // expect: 2
+ printf("%d\n", findComplement(1)); // expect: 0
+}