476. Number Complement LeetCode Solution

In this guide, you will get 476. Number Complement LeetCode Solution with the best time and space complexity. The solution to Number Complement problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Number Complement solution in C++
  4. Number Complement solution in Java
  5. Number Complement solution in Python
  6. Additional Resources
476. Number Complement LeetCode Solution image

Problem Statement of Number Complement

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 in its binary representation.

For example, The integer 5 is “101” in binary and its complement is “010” which is the integer 2.

Given an integer num, return its complement.

Example 1:

Input: num = 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.

Example 2:

Input: num = 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.

Constraints:

1 <= num < 231

Note: This question is the same as 1009: https://leetcode.com/problems/complement-of-base-10-integer/

Complexity Analysis

  • Time Complexity: O(32) = O(1)
  • Space Complexity: O(1)

476. Number Complement LeetCode Solution in C++

class Solution {
 public:
  int findComplement(long num) {
    for (long i = 1; i <= num; i <<= 1)
      num ^= i;
    return num;
  }
};
/* code provided by PROGIEZ */

476. Number Complement LeetCode Solution in Java

class Solution {
  public int findComplement(int num) {
    for (long i = 1; i <= num; i <<= 1)
      num ^= i;
    return num;
  }
}
// code provided by PROGIEZ

476. Number Complement LeetCode Solution in Python

N/A
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.