Skip to content

Commit 6a6c5be

Browse files
committed
feat(boolean_algebra): add half adder Implementation
1 parent ae68a78 commit 6a6c5be

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

boolean_algebra/half_adder.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
"""
2+
A Half Adder is a basic combinational circuit in digital logic.
3+
It computes the sum and carry outputs for two input bits.
4+
5+
Truth Table:
6+
-------------------------
7+
| Input A | Input B | Sum | Carry |
8+
-------------------------
9+
| 0 | 0 | 0 | 0 |
10+
| 0 | 1 | 1 | 0 |
11+
| 1 | 0 | 1 | 0 |
12+
| 1 | 1 | 0 | 1 |
13+
-------------------------
14+
15+
Refer - https://en.wikipedia.org/wiki/Adder_(electronics)#Half_adder
16+
"""
17+
18+
19+
def half_adder(a: int, b: int) -> tuple[int, int]:
20+
"""
21+
Compute the sum and carry for a Half Adder.
22+
23+
>>> half_adder(0, 0)
24+
(0, 0)
25+
>>> half_adder(0, 1)
26+
(1, 0)
27+
>>> half_adder(1, 0)
28+
(1, 0)
29+
>>> half_adder(1, 1)
30+
(0, 1)
31+
32+
Raises:
33+
ValueError: If inputs are not 0 or 1.
34+
"""
35+
if a not in (0, 1) or b not in (0, 1):
36+
raise ValueError("Inputs must be 0 or 1")
37+
38+
sum_bit = a ^ b
39+
carry_bit = a & b
40+
return sum_bit, carry_bit
41+
42+
43+
if __name__ == "__main__":
44+
import doctest
45+
46+
doctest.testmod()

0 commit comments

Comments
 (0)