×

XNOR operator in Java

The opposite of the binary equivalent of XOR is given by XNOR.

Truth table:

XYXNOR
001
010
100
111

If the bits are the same, it returns 1, else it returns 0.

Examples: 

Input: 10 20

Output : 1

A Binary of 20 is 10100

A Binary of 10 is  1010

So the XNOR is  00001

So the output is 1

Input  : 10 10

Output : 15

A Binary of 10 is  1010

A Binary of 10 is  1010

So the XNOR is   1111

So the output is 15

Method 1:- (O(logn))

In this solution, each bit is checked separately. If two bits match, we output 1; otherwise, we output 0.

Let's explain it using the following code.

XNORExpl1.java

// Java program to calculate
// XNOR of two numbers
import java.util.*;
import java.lang.*;
 
public class XNORExpl1 {
 
    public static int xnor(int x, int y)
    {
        // x should be larger
        if (x < y) {
            // swapping x and y;
            int temp = x;
            x = y;
            y = temp;
        }
 
        if (x == 0 && y == 0)
            return 1;
 
        // for last bit of x
        int x_rem = 0;
 
        // for the last bit of y
        int y_rem = 0;
 
        // counter for c bit
        // and set bit in xnorn
        int c = 0;
 
        // to make new xnor number
        int xnorn = 0;
 
        // for set bits in new xnor number
        while (true) {
            // get last bit of x
            x_rem = x & 1;
 
            // get the last bit of y
            y_rem = y & 1;
 
            // Checking if the current two bits are the same
            if (x_rem == y_rem)
                xnorn |= (1 << c);
 
            // counter for c bit
            c++;
            x = x >> 1;
            y = y >> 1;
            if (x < 1)
                break;
        }
        return xnorn;
    }
 
    // Driver code
    public static void main(String args[])
    {
        int x = 10, y = 50;
        System.out.println(xnor(x, y));
    }
}

Output:

XNOR operator in Java

Second Method:- O(1) 

1) Determine the maximum of the two provided numbers.

2) Flip the highest two numbers' bits.

3) Return the XOR of the bigger original number and the smaller changed number.

XNORExpl2.java

// Java program to calculate XNOR
// of two numbers
import java.io.*;
 
class XNORExpl2 {
     
    
    static int togglebit(int m)
    {
        if (m == 0)
            return 1;
 
        // copying m as we are
        // going to change it.
        int j = m;
 
        // Below steps set bits after
        // MSB (including MSB)
 
        m |= m >> 1;
 
        // This makes sure 4 bits
        // (From MSB and including MSB)
        // are set. It does following
        // 110011001 | 001100110 = 111111111
        m |= m >> 2;
        m |= m >> 4;
        m |= m >> 8;
        m |= m >> 16;
 
        return j ^ m;
    }
 
    // Returns XNOR of n1 and n2
    static int xnor(int n1, int n2)
    {
        // if n2 is greater then
        // swap this number in n1 
        if (n1 < n2)
        {
            int t = n1;
            n1 = n2;
            n2 = t;
        }
     
        n1 = togglebit(n1);
     
        return n1 ^ n2;
    }
 
    /* Driver code to test above method */
    public static void main(String args[])
    {
        int x = 10, y = 20;    
        System.out.println(xnor(x, y));
    }
}

Output:

XNOR operator in Java

Third Method: Using XOR

Simply said, A XOR B is the opposite of XNOR of A and B. A bit mask must be created in order to only retrieve the real bits from an inverted binary number because directly inverting any binary number also flips the leading zeroes.

Below is an example of this implementation:

XNORExpl3.java

// Java program to find XNOR of two numbers.
class XNORExpl3 {
 
  // Returns XNOR of n1 and n2
  static int XNOR(int x, int y)
  {
    // getting the number of bits from
    // max of x and y to construct the bit mask
    int nOB = (int)(Math.log(Math.max(x, y)) / Math.log(2));
 
    // constructing the bit m
    int m = (1 << nOB) - 1;
 
    // x = inverted xor
    int x1 = ~(x ^ y);
 
    // getting only the required bits
    // using the m
    return x1 & m;
  }
 
  // Main method
  public static void main(String args[])
  {
    int n1 = 7, n2 = 19;
 
    // calling the function
    System.out.print(XNOR(n1, n2));
  }
}

Output:

XNOR operator in Java

Time Complexity: O(1)

Auxiliary Space: O(1)


Related Topics

Upcasting and Downcasting in Java

Type casting in Java is an important and very interesting topic to deal with. But here upcasting and downcasting is somewhat related to typecasting. In normal typecasting, we convert from...

6 minutes read.

Converting Roman to Integer Numerals in java

In this article, you will be acknowledged about the process of conversion of roman numbers to integers in java. The most important approaches are discussed and also the implementation of...

3 minutes read.

How to compare three dates in Java?

While using the date and the time in Java, we occasionally have to compare the dates. Java does not compare dates the same way it compares the two numbers. Therefore,...

6 minutes read.

Types of Events in Java

One of Java's key ideas is the principle of an event. Events in Java are activities that result in a change in the state or behavior of an object. The...

4 minutes read.

Two Decimal Places Java

When a double data type is used in Java before a variable, this indicates 15 digits after decimal point. However, there are situations when we only require 2 decimal places...

4 minutes read.

Heart Pattern in Java

Heart Pattern is yet another intricate pattern program, however, due to its complexity, interviewers hardly ever inquire about it. Method for Printing the Heart Number Pattern Put the value of the total row...

2 minutes read.

How to make Java Projects

Ant and Maven are both offered by NetBeans for the development of Java applications. When using Ant, the IDE creates an Ant build script depending on the settings you select...

6 minutes read.

What are Array strings in Java?

In normal programming, An array is a group and a collection of identical forms of data that are stored in a sequential memory region and may be accessed using their...

4 minutes read.

Differences between Lock and Monitor in Java Concurrency

In this tutorial, we will discuss the overview of Lock and Monitor and the differences between them. Introduction Java Concurrency is the ability to perform specific tasks at a time parallelly. The...

4 minutes read.

Java Math with Methods and Examples

Java Math class contains various methods for performing math operations like min(), max(), avg() and various trigonometric functions like sin(), cos(), tan() etc. Methods: The java.lang.Math class contains various methods for performing...

5 minutes read.

Generic Linked List in Java

A linear data structure known as a Linked List stores values in nodes. As we already know, each node has two properties: its value and a link to the node...

6 minutes read.

Java Byte intValue() method

The intValue()  method of Java Integer class returns an int value for this Integer.  Syntax public int intValue()  Parameters NA  Specified by This method is specified by intValue in class Number  Return Value This method returns the numeric...

1 minute read.

Find Unique Elements in Array Java

An array in Java is a grouping of objects that share the same type of data. We are free to enter identical or repeating elements into an array. Therefore, we...

6 minutes read.

Thread Synchronization in Java

In Java, the smallest processing component is a thread, which is a small subprocess. It follows a different course of action. Threads are autonomous. If an exception occurs in one thread,...

6 minutes read.

JDBC vs ODBC

Difference Between JDBC and ODBC ODBC: ODBC (Open Database Connectivity) is the accepted method for accessing databases among organisations and programmers. A database is linked to other programmes, such as word processors, spreadsheets,...

4 minutes read.

Rehashing in Java

The most crucial idea mostly in the data structure is hashing, which is utilized to change a particular key into some other value. The hash function can be used to...

7 minutes read.

Tower of Hanoi Program in Java

Tower of Hanoi Program in Java The Tower of Hanoi program in Java is written to solve a mathematical puzzle, called Tower of Hanoi, where we have three poles and n...

4 minutes read.

Compile time vs Runtime in java

Introduction: This article will discuss compile time vs. runtime in java. Compile time and runtime are two programming terms utilized in software improvement. Compile time is when the source code is...

3 minutes read.

Java Integer valueOf() method

The valueOf() method of Java Integer class returns an Integer object holding the specified int value. The second method returns an Integer object holding the specified String value. The third syntax returns...

2 minutes read.

Java String copyValueOf() method

copyValueOf() method returns a String that holds the character sequence of the character array. Syntax: copyValueOf(char[] data) Parameters: data : the character array i.e. String Returns: It returns a String that contains the characters of the...

2 minutes read.