From 856168384d4c802eb531683829606db25925b6dc Mon Sep 17 00:00:00 2001 From: Alexander Pantyukhin Date: Wed, 16 Nov 2022 04:27:22 +0400 Subject: [PATCH] feat: add compliment of 10 integer (#1136) * add complinent of 10 integer * Update 1009.c add new line at the end * Rename README.md to DIRECTORY.md change filename * chore: apply suggestions from code review Co-authored-by: David Leal --- leetcode/DIRECTORY.md | 1 + leetcode/src/1009.c | 15 +++++++++++++++ 2 files changed, 16 insertions(+) create mode 100644 leetcode/src/1009.c diff --git a/leetcode/DIRECTORY.md b/leetcode/DIRECTORY.md index 9ce6a443..56051ab4 100644 --- a/leetcode/DIRECTORY.md +++ b/leetcode/DIRECTORY.md @@ -90,6 +90,7 @@ | 938 | [Range Sum of BST](https://leetcode.com/problems/range-sum-of-bst/) | [C](./src/938.c) | Easy | | 965 | [Univalued Binary Tree](https://leetcode.com/problems/univalued-binary-tree/) | [C](./src/965.c) | Easy | | 977 | [Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/) | [C](./src/977.c) | Easy | +| 1009 | [Complement of Base 10 Integer](https://leetcode.com/problems/complement-of-base-10-integer/) | [C](./src/1009.c) | Easy | | 1089 | [Duplicate Zeros](https://leetcode.com/problems/duplicate-zeros/) | [C](./src/1089.c) | Easy | | 1184 | [Distance Between Bus Stops](https://leetcode.com/problems/distance-between-bus-stops/) | [C](./src/1184.c) | Easy | | 1189 | [Maximum Number of Balloons](https://leetcode.com/problems/maximum-number-of-balloons/) | [C](./src/1189.c) | Easy | diff --git a/leetcode/src/1009.c b/leetcode/src/1009.c new file mode 100644 index 00000000..77480d71 --- /dev/null +++ b/leetcode/src/1009.c @@ -0,0 +1,15 @@ +// Bit manipulation. +// - Find the bit length of n using log2 +// - Create bit mask of bit length of n +// - Retun ~n and bit of ones mask +// Runtime: O(log2(n)) +// Space: O(1) + +int bitwiseComplement(int n){ + if (n == 0){ + return 1; + } + + int binary_number_length = ceil(log2(n)); + return (~n) & ((1 << binary_number_length) - 1); +}