Skip to content
Programming101
Programming101

Learn everything about programming

  • Home
  • CS Subjects
    • IoT – Internet of Things
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programming101

Learn everything about programming

Leetcode Number Complement problem solution

YASH PAL, 31 July 2024

In this Leetcode Number Complement problem solution 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.

Leetcode Number Complement problem solution

Problem solution in Python.

class Solution:
    def findComplement(self, num: int) -> int:
        b = bin(num)[2:]
        b = b.replace('1','2')
        b = b.replace('0', '1')
        b = b.replace('2','0')
        return int(b,2)

Problem solution in Java.

class Solution {
    public int findComplement(int num) {
        int r = 0;
        int i=1;
        while(num>i && i>0) {
            r += (num^i)&i;
            i = (i<<1);
        }
        return r;
    }
}

Problem solution in C++.

class Solution {
public:
    int findComplement(int num) {
        int res = 0;
        for(int shift = 0; num; ++shift, num >>= 1)
            res |= !(num & 1) << shift;
        return res;
    }
};

Problem solution in C.

int findComplement(int num){
        unsigned int msb  = ~0; int temp = num;
        while (temp){
                temp = temp >> 1;
                msb = msb << 1;
        }
        return (~num & ~msb);
}

coding problems

Post navigation

Previous post
Next post
  • HackerRank Separate the Numbers solution
  • How AI Is Revolutionizing Personalized Learning in Schools
  • GTA 5 is the Game of the Year for 2024 and 2025
  • Hackerrank Day 5 loops 30 days of code solution
  • Hackerrank Day 6 Lets Review 30 days of code solution
How to download udemy paid courses for free

Pages

  • About US
  • Contact US
  • Privacy Policy

Programing Practice

  • C Programs
  • java Programs

HackerRank Solutions

  • C
  • C++
  • Java
  • Python
  • Algorithm

Other

  • Leetcode Solutions
  • Interview Preparation

Programming Tutorials

  • DSA
  • C

CS Subjects

  • Digital Communication
  • Human Values
  • Internet Of Things
©2025 Programming101 | WordPress Theme by SuperbThemes