A comparator is a combinational circuit that tells whether one number is smaller than, equal to or bigger than another. A 2-bit comparator looks at the high bits first, and at the low bits only if the high bits are equal.
What to build
Print the three outputs of a 2-bit comparator for two numbers.
Requirements
- The outputs are
lt(A < B),eq(A = B) andgt(A > B), in that order. - Exactly one of the three outputs is 1.
- Work with the bits as a circuit would: do not compare the numbers directly with
<or>.
Input
One line with two numbers a and b, each from 0 to 3.
Output
One line with lt, eq and gt as three bits.
Constraints
0 ≤ a, b ≤ 3.
Example
Input:
2 1
Output:
0 0 1
Why it works
The high bit has more weight than the low bit, so if the high bits differ, they decide the answer. Only when they are equal does the comparison go on to the low bits. The same idea, bit by bit from the left, works for any width.
Examples
2 1
0 0 1
3 3
0 1 0
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Split each number into its two bits: a1 = a >> 1, a0 = a & 1, and the same for b.
Hint 2
The numbers are equal when both pairs of bits are equal: eq = (a1 == b1) and (a0 == b0).
Hint 3
A > B when the high bits decide it (a1 = 1, b1 = 0), or the high bits are equal and the low bits decide it.
Solution
Show one correct solution (try it yourself first)
a, b = map(int, input().split()) a1, a0 = a >> 1, a & 1 b1, b0 = b >> 1, b & 1 eq1 = 1 - (a1 ^ b1) eq0 = 1 - (a0 ^ b0) gt = (a1 & (1 - b1)) | (eq1 & a0 & (1 - b0)) lt = ((1 - a1) & b1) | (eq1 & (1 - a0) & b0) print(lt, eq1 & eq0, gt)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step