[
math
bit manipulation
]
Leetcode 1009. Complement of Base 10 Integer
https://leetcode.com/problems/complement-of-base-10-integer
What we actually need to find in this problem is length of our number in bits: if we have 10 = 1010
, then complementary is 5 = 101
. Note, that 5 + 10 = 15 = 2^4 - 1
. So, let us just find length of our number in bits and subtract N-1
.
Complexity time complexity is O(log N)
to find its length; space complexity is also O(log N)
to keep binary representation of our number.
class Solution:
def bitwiseComplement(self, N):
return (1<<(len(bin(N)) - 2)) - 1 - N
If you like the solution, you can upvote it on leetcode discussion section: Problem 1009