Algorithm


Problem Name: 476. 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

Code Examples

#1 Code Example with C Programming

Code - C Programming


int findComplement(int num) {
    int i, k = 0;
    if (!num) return 1;
    for (i = 0; num && i  <  32; i ++) {
        if (!(num & (1 << i))) {
            k |= (1 << i);
        } else {
            num &= ~(1 << i);
        }
    }
    return k;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
num = 5

Output

x
+
cmd
2

#2 Code Example with Javascript Programming

Code - Javascript Programming


const findComplement = function(num) {
  const toBin = num => (num >>> 0).toString(2)
  const flip = str => {
    let res = ''
    for(let c of str) res += (c === '1' ? '0' : '1')
    return res
  }
  return parseInt(flip(toBin(num)), 2)
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
num = 5

Output

x
+
cmd
2

#3 Code Example with Python Programming

Code - Python Programming


class Solution:
    def findComplement(self, num):
        """
        :type num: int
        :rtype: int
        """
        return int("".join([str((int(i)+1)%2) for i in bin(num)[2:]]),2)
Copy The Code & Try With Live Editor

Input

x
+
cmd
num = 1

#4 Code Example with C# Programming

Code - C# Programming


namespace LeetCode
{
    public class _0476_NumberComplement
    {
        public int FindComplement(int num)
        {
            int mask = 1;
            while (mask  <  num)
                mask = (mask << 1) | 1;
            return num ^ mask;
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
num = 1
Advertisements

Demonstration


Previous
#475 Leetcode Heaters Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#477 Leetcode Total Hamming Distance Solution in C, C++, Java, JavaScript, Python, C# Leetcode