Number Complement LeetCode Solution - The Coding Shala

Home >> LeetCode >> Number Complement

 In this post, we will learn how to solve LeetCode's Number Complement Problem and will implement its solution in Java.

Number Complement Problem

Given a positive integer num, output its complement number. The complement strategy is to flip the bits of its binary representation.

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.

Practice this problem on LeetCode.

LeetCode - Number Complement Java Solution

Approach 1

Just flip the bit and make decimal value from it.

Java Program: 

class Solution {
    public int findComplement(int num) {
        int ans = 0;
        int two = 1;
        while(num > 0) {
            //if bit is 0 then flip and make binary of result
            if(num%2 == 0) {
                ans += two;
            }
            two *= 2;
            num /= 2;
        }
        return ans;
    }
}

Approach 2

Using bit Manipulation.

Java Program: 

class Solution {
    public int findComplement(int num) {
        int ans = 0;
        int i = 31;
        //find first 1 from left
        while(num >> i == 0) i--;
        while(i >= 0) {
            //flip the bit
            if(((num >> i) & 1) == 0) {
                ans |= 1 << i;
            }
            i--;
        }
        return ans;
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

LeetCode - Bulb Switcher Solution - The Coding Shala

Anti Diagonals - The Coding Shala

Sorting the Sentence LeetCode Solution - The Coding Shala

Java Method Overloading - The Coding Shala