XOR using NAND gates

Create an XOR gate using only NAND gates.  (BTW, mostly all circuit problems assume you have two inputs plus 0 and 1 also as inputs).

Solution

You may be able to find the solution on the discussion forum.

💡Strategies for Solving This Problem

Logic Gates and Boolean Algebra

Got this at a systems programming interview. Tests understanding of digital logic and boolean algebra. Important for low-level programming and computer architecture.

The Problem

Implement XOR using only NAND gates. NAND is "universal" - you can build any logic gate from it.

Background

NAND truth table:

A  B  | NAND
0  0  |  1
0  1  |  1
1  0  |  1
1  1  |  0

XOR truth table:

A  B  | XOR
0  0  |  0
0  1  |  1
1  0  |  1
1  1  |  0

Why NAND is Universal

You can build NOT, AND, OR from NAND:

  • NOT A: NAND(A, A)
  • AND: NOT(NAND(A, B))
  • OR: NAND(NOT A, NOT B)

Building XOR

XOR = (A AND NOT B) OR (NOT A AND B)

So we need to express this using only NAND.

The Solution Pattern

XOR can be built with 4 NAND gates:

  1. nand1 = NAND(A, B)
  2. nand2 = NAND(A, nand1)
  3. nand3 = NAND(B, nand1)
  4. result = NAND(nand2, nand3)

Why It Works

Let's trace through:

  • nand1 = NAND(A, B) = NOT(A AND B)
  • nand2 = NAND(A, nand1) = NOT(A AND NOT(A AND B)) = NOT A OR B
  • nand3 = NAND(B, nand1) = NOT(B AND NOT(A AND B)) = NOT B OR A
  • result = NAND(nand2, nand3) = NOT((NOT A OR B) AND (NOT B OR A))

Through boolean algebra, this reduces to A XOR B.

Alternative: Using 5 NAND Gates

First build NOT, AND, OR, then combine:

  1. NOT A = NAND(A, A)
  2. NOT B = NAND(B, B)
  3. Then use formula: XOR = (A AND NOT B) OR (NOT A AND B)

This uses 5 gates but is easier to understand.

Scroll to Top