LeetCode 476: Number Complement Solution
Master LeetCode problem 476 (Number Complement), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
476. Number Complement
Problem Explanation
Explanation:
To find the complement of an integer, we need to flip all the bits in its binary representation. We can achieve this by iterating through each bit of the number and toggling it (flipping 1 to 0 and 0 to 1). We can do this by using XOR operation with a bitmask that has all 1's of the same length as the number.
- Find the number of bits needed to represent the given number.
- Create a bitmask with all 1's of the same length as the number.
- XOR the number with the bitmask to get the complement.
Time Complexity: The time complexity of this approach is O(log n) where n is the given number.
Space Complexity: The space complexity is O(1) as we are using only a constant amount of extra space.
Solution Code
class Solution {
public int findComplement(int num) {
int mask = (Integer.highestOneBit(num) << 1) - 1;
return num ^ mask;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 476 (Number Complement)?
This page provides optimized solutions for LeetCode problem 476 (Number Complement) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 476 (Number Complement)?
The time complexity for LeetCode 476 (Number Complement) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 476 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 476 in Java, C++, or Python.