leetcode

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

commit 378fbb0034a1d49b261f540a4b3cf0049e8b6803
parent 1936828618e8dfff65ac1f88e806873f92d848fd
Author: Jack Sangdahl <jack@pngu.org>
Date:   Tue, 10 Mar 2026 20:28:54 -0600

1009. complement of base 10 integer

Diffstat:
Mcomplement_base_10_int.c | 22+++++++++++++++-------
Mcomplement_base_10_int.py | 5+----
2 files changed, 16 insertions(+), 11 deletions(-)

diff --git a/complement_base_10_int.c b/complement_base_10_int.c @@ -8,14 +8,22 @@ */ int bitwiseComplement(int n) { - int c = 1; - while (c < n) - c = (c << 1) + 1; - return n ^ c; + if (!n) + return 1; + unsigned int mask = ~0; + while (mask & n) + mask <<= 1; + return ~n ^ mask; } int main() { - printf("%d\n", bitwiseComplement(5)); // expect: 2 - printf("%d\n", bitwiseComplement(7)); // expect: 0 - printf("%d\n", bitwiseComplement(10)); // expect: 5 + int r1 = bitwiseComplement(5); + int r2 = bitwiseComplement(7); + int r3 = bitwiseComplement(10); + printf("%d\n", r1); // expect: 2 + assert(r1 == 2); + printf("%d\n", r2); // expect: 0 + assert(r2 == 0); + printf("%d\n", r3); // expect: 5 + assert(r3 == 5); } diff --git a/complement_base_10_int.py b/complement_base_10_int.py @@ -13,10 +13,7 @@ class Solution(object): :type n: int :rtype: int """ - c = 1 - while n > c: - c = c * 2 + 1 - return c - n + return (1 << len(bin(n)) >> 2) - n - 1 if __name__ == "__main__":