Skip to content

Commit 4f12987

Browse files
committed
feat(boolean_algebra): add full adder implementation
1 parent 6a6c5be commit 4f12987

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,3 +108,4 @@ venv.bak/
108108
.try
109109
.vscode/
110110
.vs/
111+
scripts/python3.bat

boolean_algebra/full_adder.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
"""
2+
A Full Adder is a fundamental combinational circuit in digital logic.
3+
It computes the sum and carry outputs for two input bits and an input carry bit.
4+
5+
Truth Table:
6+
-----------------------------------------
7+
| A | B | Cin | Sum | Cout |
8+
-----------------------------------------
9+
| 0 | 0 | 0 | 0 | 0 |
10+
| 0 | 1 | 0 | 1 | 0 |
11+
| 1 | 0 | 0 | 1 | 0 |
12+
| 1 | 1 | 0 | 0 | 1 |
13+
| 0 | 0 | 1 | 1 | 0 |
14+
| 0 | 1 | 1 | 0 | 1 |
15+
| 1 | 0 | 1 | 0 | 1 |
16+
| 1 | 1 | 1 | 1 | 1 |
17+
-----------------------------------------
18+
19+
Refer:
20+
https://en.wikipedia.org/wiki/Adder_(electronics)#Full_adder
21+
"""
22+
23+
24+
def full_adder(a: int, b: int, cin: int) -> tuple[int, int]:
25+
"""
26+
Compute the sum and carry-out for a Full Adder.
27+
28+
Args:
29+
a: First input bit (0 or 1).
30+
b: Second input bit (0 or 1).
31+
cin: Carry-in bit (0 or 1).
32+
33+
Returns:
34+
A tuple `(sum_bit, carry_out)`.
35+
36+
>>> full_adder(0, 0, 0)
37+
(0, 0)
38+
>>> full_adder(0, 1, 0)
39+
(1, 0)
40+
>>> full_adder(1, 0, 0)
41+
(1, 0)
42+
>>> full_adder(1, 1, 0)
43+
(0, 1)
44+
>>> full_adder(0, 0, 1)
45+
(1, 0)
46+
>>> full_adder(1, 1, 1)
47+
(1, 1)
48+
49+
Raises:
50+
ValueError: If any input is not 0 or 1.
51+
"""
52+
if a not in (0, 1) or b not in (0, 1) or cin not in (0, 1):
53+
raise ValueError("Inputs must be 0 or 1.")
54+
55+
# Sum is XOR of the inputs
56+
sum_bit = a ^ b ^ cin
57+
58+
# Carry-out is true if any two or more inputs are 1
59+
carry_out = (a & b) | (b & cin) | (a & cin)
60+
61+
return sum_bit, carry_out
62+
63+
64+
if __name__ == "__main__":
65+
import doctest
66+
67+
doctest.testmod()

0 commit comments

Comments
 (0)