Write pseudocode for adding two integers in binary expansions formally. Store the two binary integers and their sum in arrays. Illustrate your algorithm using this following two integers: a = (1110) 2 and b = (1011) 2
时间: 2023-06-10 09:07:26 浏览: 118
BinaryStringCalculator:两个二进制字符串相加的算法
Here's an algorithm for adding two binary integers a and b:
```
1. Initialize carry as 0
2. Initialize index as the length of a and b arrays minus 1
3. Initialize an empty array for the sum
4. While index is greater than or equal to 0:
a. Compute the sum of the current bits in a, b, and carry
b. If the sum is 0 or 1, append it to the sum array and set carry to 0
c. If the sum is 2, append 0 to the sum array and set carry to 1
d. If the sum is 3, append 1 to the sum array and set carry to 1
e. Decrement index by 1
5. If carry is 1, append it to the sum array
6. Reverse the sum array to get the final result
```
Using the example integers a = (1110) 2 and b = (1011) 2 :
```
a = [1, 1, 1, 0]
b = [1, 0, 1, 1]
carry = 0
index = 3
sum = []
while index >= 0:
current_sum = a[index] + b[index] + carry
if current_sum == 0 or current_sum == 1:
sum.append(current_sum)
carry = 0
elif current_sum == 2:
sum.append(0)
carry = 1
else:
sum.append(1)
carry = 1
index -= 1
if carry == 1:
sum.append(carry)
sum.reverse()
result = sum # [1, 1, 1, 0, 1]
```
Therefore, (1110) 2 + (1011) 2 = (11101) 2
阅读全文