One adder can also subtract: A − B = A + B' + 1, where B' flips every bit of B.
What to build
Subtract two n-bit numbers with an adder, and print the result, the carry out and the signed overflow flag.
Requirements
- Flip every bit of B, and use a carry in of 1.
- Print the result in
nbinary digits, then the carry out (0 or 1), then the overflow flag (0 or 1), separated by spaces. - The carry out is 1 when A ≥ B as unsigned numbers (no borrow). The overflow flag is 1 when the signed (two's complement) result does not fit in
nbits.
Input
One line with n (1 to 8) and two numbers a and b in decimal, each from 0 to 2ⁿ − 1 (they are unsigned values; read them as n-bit patterns).
Output
One line: the n-bit result, the carry out and the overflow flag.
Constraints
1 ≤ n ≤ 8.
Example
Input:
4 7 5
Output:
0010 1 0
Why it works
A − B is the same as A + (−B), and in two's complement −B is B' + 1. Adding B' with a carry in of 1 does both steps in one pass of the adder. When there is no borrow, the sum overflows the n bits, which is why the carry out is 1 for A ≥ B. Signed overflow is a different thing: it needs A and B of different signs and a result with the sign of B.
Examples
4 7 5
0010 1 0
4 5 7
1110 0 0
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Flip every bit of b with b ^ mask, where mask is 2ⁿ − 1, and add 1 by setting the first carry in to 1.
Hint 2
The result is the sum of the n-bit adder: (a + (b ^ mask) + 1) & mask. The carry out is the bit above it.
Hint 3
Signed overflow happens when a and b have different signs and the result's sign is different from a's sign (the top bits).
Solution
Show one correct solution (try it yourself first)
n, a, b = map(int, input().split()) mask = (1 << n) - 1 total = a + (b ^ mask) + 1 result = total & mask carry = total >> n top = 1 << (n - 1) sa, sb, sr = bool(a & top), bool(b & top), bool(result & top) overflow = 1 if (sa != sb and sr != sa) else 0 print(format(result, "0" + str(n) + "b"), carry, overflow)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step