注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
本帖最后由 sy10017667 于 2015-4-7 11:52 编辑
Consider the problem of adding 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.
why it will be shored at (n+1) element array.
A=⟨a1,a2,…,an⟩
B=⟨b1,b2,…,bn⟩
why add A and B together will for m. where is the extra elment come from?
C=⟨c1,c2,…,cn+1⟩
the following are the full Q&A,
If it is a silly question, sorrying for asking.
Consider the problem of adding 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.
I'm just happy that I don't need to write the loop invariant, since that seems tedious. The formal statement:
Input: An array of booleans A=⟨a1,a2,…,an⟩, an array of booleans B=⟨b1,b2,…,bn⟩, each representing an integer stored in binary format (each digit is a number, either 0 or 1, least-significant digit first) and each of length n. Output: An array C=⟨c1,c2,…,cn+1⟩ that such that C′=A′+B′, where A′, B′ and C′ are the integers, represented by A, B and C.
Here is the pseudocode: ADD-BINARY(A, B): C = new integer[A.length + 1] carry = 0 for i = 1 to A.length C[i] = (A[i] + B[i] + carry) % 2 // remainder carry = (A[i] + B[i] + carry) / 2 // quotient C[i] = carry return C
|