Write a program to find 1s complement of a number in java


This is a Java program that demonstrates the concept of one's complement. The program defines a class Ones_Complement with two methods totalBits and complement.

The totalBits method takes an integer num as input and returns the total number of bits required to represent that number.

The complement method takes an integer num as input and prints the one's complement of that number. If num is negative, it prints the two's complement of the number. Otherwise, it calculates the one's complement of the number and prints it.

The main method creates an object of the Ones_Complement class and calls the complement method with an input value of 23.

Source Code

public class Ones_Complement
{
    public int totalBits(int num)
    {
        return (int)(Math.log(num) / Math.log(2)) + 1;
    }
    public void complement(int num)
    {
        System.out.print("Number : " + num);
        if (num < 0)
        {
            System.out.print("\n1s Complement : " + (~num));
        }
        else
        {
            int ones = ((1 << totalBits(num)) - 1) ^ num;
            System.out.print("\n1s Complement : " + ones);
        }
    }
    public static void main(String[] args)
    {
        Ones_Complement o = new Ones_Complement();
        o.complement(23);
    }
}

Output

Number : 23
1s Complement : 8

Example Programs