算法导论之两个N位二进制数的相加

两个n 位的二进制数据的相加问题

Consider the problem:

add two n-bit binary integers, stored in two n-element arrays A and B. The sum of the two integers should be stored in binary form in an (n+1)-element array C.


State the problem formally and write pseudocode for adding the two integers.

The problem can be formally stated as:

Input: Two n-bit binary integers stored in two nn-element array of binary digits (either 0 or 1) A=〈a1,a2,...,an〉 and B=〈b1,b2,...,bn〉.

Output: A (n+1)-bit binary integer stored in (n+1)-element array of binary digits (either 0 or 1) C=〈c1,c2,...,cn+1〉such that C=A+B.

Binary——add(A,B)的伪代码写法:(伪代码代表不可以直接运行需要进行相应的具体编程环境的书写更改)


n = A.length
// A and B have the same length

for i = 1 to (n + 1)
    C[i] = 0
// initiation the C

carry = 0
// gain initiate
 
for i = n down to 1
    C[i] = (A[i] + B[i] + carry) % 2
    carry = (A[i] + B[i] + carry) / 2
C[i] = carry

return C

Note: As we are adding number represented in binary, we have to start bit by bit addition from the least significant digit.

算法导论之两个二进制n 位数组相加

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值