Python二进制加法程序异常咨询:前导零与补零后计算错误
Let's walk through fixing the two issues in your code step by step—they're both easy to spot once you know what to look for!
Issue 1: Incorrect Pre-padding for Length Alignment
Your current code uses string comparison (b > a or a > b) to decide which number to pad with leading zeros. This is wrong because string comparison checks character order (e.g., "010" is considered less than "10" because '0' comes before '1'), not the actual length of the binary numbers. This leads to padding the wrong number, which breaks the alignment and the final result.
Fix:
Compare the lengths of the two input strings instead. Pad the shorter string with leading zeros until both are the same length.
Issue 2: Erasing Carry Value When Processing '0' Bits
In your loop, when a bit is '0', you're setting x = 0—this completely discards the carry value from the previous bit calculation. For example, if carry was 1 and the current bit is 0, x should stay 1 (carry + 0), not get reset to 0. This is why inputs with leading zeros produce wrong results—those zeros trigger this incorrect reset.
Fix:
Instead of resetting x to 0, add 0 to x when the bit is '0' (so the carry value is preserved).
Corrected Code
a = input('Enter first binary number\t') b = input('Enter second binary number\t') carry = 0 answer = "" # Fix 1: Pad based on length, not string comparison len_a = len(a) len_b = len(b) if len_a < len_b: a = '0' * (len_b - len_a) + a elif len_b < len_a: b = '0' * (len_a - len_b) + b print(a) print(b) for i in range(len(a)-1, -1, -1): x = carry # Fix 2: Add 1 if bit is '1', else add 0 (preserve carry) x += 1 if a[i] == '1' else 0 x += 1 if b[i] == '1' else 0 # Determine current bit of the answer answer = '1' + answer if x % 2 == 1 else '0' + answer # Update carry for next iteration carry = 1 if x >= 2 else 0 if carry == 1: answer = '1' + answer print(answer)
Testing the Fixes
- Leading zero input: Try
a = "010"andb = "001"—the code will correctly output"011"(you can add extra logic to trim leading zeros if needed). - Different length inputs: Try
a = "10"andb = "101"—the code padsato"010", then computes010 + 101 = 111, which is correct.
内容的提问来源于stack exchange,提问作者Joseph

