File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ Problem Link: https://leetcode.com/problems/complement-of-base-10-integer/
3+
4+ 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
5+ in its binary representation.
6+ For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2.
7+ Given an integer n, return its complement.
8+
9+ Example 1:
10+ Input: n = 5
11+ Output: 2
12+ Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.
13+
14+ Example 2:
15+ Input: n = 7
16+ Output: 0
17+ Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10.
18+
19+ Example 3:
20+ Input: n = 10
21+ Output: 5
22+ Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.
23+
24+ Constraints:
25+ 0 <= n < 109
26+ """
27+ # Time Complexity: O(logN)
28+ class Solution :
29+ def bitwiseComplement (self , n : int ) -> int :
30+ mask = 1
31+
32+ """
33+ (number) => (how-number-is-derived)=>binary-string
34+ mask = 1 => 1 => 1
35+ mask = 3 => (2*1 + 1) => 11
36+ mask = 7 => (3*2 + 1) => 111
37+ mask = 15 => (7*2 + 1) => 1111
38+ """
39+ while mask < n :
40+ mask = mask * 2 + 1
41+
42+ return mask ^ n
You can’t perform that action at this time.
0 commit comments