leetcode

Leetcode Solutions (0x6A73)
git clone https://git.pngu.org/leetcode
Log | Files | Refs | Submodules | README

commit b1b4bfa3a2c70bf364080ccf0e0014cd6ae80054
parent c7a993946c13641bd0faadce68e2156e94a92e14
Author: Jack Sangdahl <jack@pngu.org>
Date:   Wed, 17 Dec 2025 09:49:41 -0700

1009. complement of base 10 integer

Diffstat:
Acomplement_base_10_int.c | 21+++++++++++++++++++++
Acomplement_base_10_int.py | 26++++++++++++++++++++++++++
2 files changed, 47 insertions(+), 0 deletions(-)

diff --git a/complement_base_10_int.c b/complement_base_10_int.c @@ -0,0 +1,21 @@ +// 1009. Complement of Base 10 Integer +#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. given an integer + * 'n', return its complement. + */ + +int bitwiseComplement(int n) { + int c = 1; + while (c < n) + c = (c << 1) + 1; + return n ^ c; +} + +int main() { + printf("%d\n", bitwiseComplement(5)); // expect: 2 + printf("%d\n", bitwiseComplement(7)); // expect: 0 + printf("%d\n", bitwiseComplement(10)); // expect: 5 +} diff --git a/complement_base_10_int.py b/complement_base_10_int.py @@ -0,0 +1,26 @@ +# 1009. Complement of Base 10 Integer + +""" +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. given an integer +'n', return its complement. +""" + + +class Solution(object): + def bitwiseComplement(self, n): + """ + :type n: int + :rtype: int + """ + c = 1 + while n > c: + c = c * 2 + 1 + return c - n + + +if __name__ == "__main__": + obj = Solution() + print(obj.bitwiseComplement(n=5)) + print(obj.bitwiseComplement(n=7)) + print(obj.bitwiseComplement(n=10))