Leetcode 1009. Complement of Base 10 Integer
Leetcode Problem 1009: Complement of Base 10 Integer
Given a positive integer n
, you need to find the complement of its binary representation. The complement strategy is to flip the bits of its binary representation.
Example 1:
n = 5
2
5
is 101
, and its complement is 010
, which is 2
in base-10.Example 2:
n = 1
0
1
is 1
, and its complement is 0
, which is 0
in base-10.0
?
0
is 1
, according to the description of bit flipping.n
?
n
will be within the bounds of a 32-bit signed integer.n
into its binary form.n
.n
.1
for the length of the binary representation.public class ComplementBase10Integer {
public int bitwiseComplement(int n) {
// Edge case: when n is 0, the complement is 1
if (n == 0) return 1;
// Determine the bit length of n
int bitLength = Integer.toBinaryString(n).length();
// Create a mask of the same length with all bits set to 1
int mask = (1 << bitLength) - 1;
// XOR n with the mask to get the complement
int complement = n ^ mask;
return complement;
}
public static void main(String[] args) {
ComplementBase10Integer solution = new ComplementBase10Integer();
System.out.println(solution.bitwiseComplement(5)); // Output: 2
System.out.println(solution.bitwiseComplement(1)); // Output: 0
System.out.println(solution.bitwiseComplement(0)); // Output: 1
}
}
The time complexity of this solution is O(1) because:
Therefore, the overall time complexity is O(1).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?