Skip to content
Programmingoneonone
Programmingoneonone
  • Engineering Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
    • 100+ C++ Programs
  • Solutions
    • HackerRank
      • Algorithms Solutions
      • C solutions
      • C++ solutions
      • Java solutions
      • Python solutions
    • Leetcode Solutions
    • HackerEarth Solutions
  • Work with US
Programmingoneonone
Programmingoneonone

Leetcode Number Complement problem solution

YASH PAL, 31 July 202422 January 2026

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

Leetcode Number Complement 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)

Number Complement 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 solutions Leetcode Problems Solutions Leetcode

Post navigation

Previous post
Next post

Leave a Reply

Your email address will not be published. Required fields are marked *

Programmingoneonone

We at Programmingoneonone, also known as Programming101 is a learning hub of programming and other related stuff. We provide free learning tutorials/articles related to programming and other technical stuff to people who are eager to learn about it.

Pages

  • About US
  • Contact US
  • Privacy Policy

Practice

  • Java
  • C++
  • C

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes