LeetCode Entry
1009. Complement of Base 10 Integer
Invert binary
1009. Complement of Base 10 Integer easy blog post substack youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1294
Problem TLDR
Invert binary #easy
Intuition
Use a bitmask of the next power of two - 1.
Approach
- Kotlin: takeHighestOneBit, countLeadingZeroBits
- Rust: leasing_zeros, next_power_of_two, ilog2
-
0 case trick: use 1 to check bits count at least 1
Complexity
-
Time complexity: \(O(1)\)
-
Space complexity: \(O(1)\)
Code
// 0ms
fun bitwiseComplement(n: Int) =
(n or 1).takeHighestOneBit()*2 - n - 1
// 0ms
pub fn bitwise_complement(n: i32) -> i32 {
n^(2<<(n|1).ilog2())-1
}