From 77f46021e62b1d16803e746db4a39d22d17700e2 Mon Sep 17 00:00:00 2001 From: Jack Sangdahl Date: Wed, 21 Aug 2024 18:52:54 -0600 Subject: 476. number complement --- number_complement.c | 16 ++++++++++++++++ number_complement.py | 26 ++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 number_complement.c create mode 100644 number_complement.py 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 +} diff --git a/number_complement.py b/number_complement.py new file mode 100644 index 0000000..149a834 --- /dev/null +++ b/number_complement.py @@ -0,0 +1,26 @@ +# 476. Number Complement + +""" +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 +""" + + +class Solution(object): + def findComplement(self, num): + """ + :type num: int + :rtype: int + """ + i = 1 + while i <= num: + i = i << 1 + return (i - 1) ^ num + + +if __name__ == "__main__": + obj = Solution() + print(obj.findComplement(5)) + print(obj.findComplement(1)) -- cgit v1.2.3