Leetcode 476. Number Complement
Given a positive integer num
, output its complement number. The complement strategy is to flip the bits of its binary representation. For instance, the binary complement of the number 5
(101
in binary) is 2
(010
in binary).
Example 1:
Input: num = 5
Output: 2
Explanation: The binary representation of 5 is 101 (5 in decimal), and its complement is 010 (2 in decimal).
Example 2:
Input: num = 1
Output: 0
Explanation: The binary representation of 1 is 1 (1 in decimal), and its complement is 0 (0 in decimal).
Constraints:
num
is guaranteed to fit within the range of a 32-bit signed integer.num >= 1
Detailed Steps:
num
.public class NumberComplement {
public int findComplement(int num) {
// Calculate the bit length of num
int bitLength = (int)(Math.log(num) / Math.log(2)) + 1;
// Create a mask with all 1s of the same bit length as num
int mask = (1 << bitLength) - 1;
// XOR num with the mask to get the complement
return num ^ mask;
}
public static void main(String[] args) {
NumberComplement nc = new NumberComplement();
// Test cases
System.out.println(nc.findComplement(5)); // Output: 2
System.out.println(nc.findComplement(1)); // Output: 0
}
}
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?