算法导论第二章第一节答案

合集下载

高中数学第二章算法初步1算法的基本思想课时作业含解析北师大版必

高中数学第二章算法初步1算法的基本思想课时作业含解析北师大版必

学习资料第二章算法初步1算法的基本思想[课时作业][A组基础巩固]1.能设计算法求解下列各式中S的值的是()①S=错误!+错误!+错误!+…+错误!;②S=错误!+错误!+错误!+…+错误!+…;③S=错误!+错误!+错误!+…+错误!(n为确定的正整数).A.①②B.①③C.②③D.①②③解析:因为算法的步骤是有限的,所以②不能设计算法求解,易知①③能设计算法求解.答案:B2.关于一元二次方程x2-5x+6=0的求根问题,下列说法正确的是()A.只能设计一种算法B.可以设计两种算法C.不能设计算法D.不能根据解题过程设计算法答案:B3.对于一般的二元一次方程组错误!在写解此方程组的算法时,需要注意的是()A.a1≠0 B.a2≠0C.a1b2-a2b1≠0 D.a1b1-a2b2≠0答案:C4.下面给出的是一个已打乱的“找出a,b,c,d四个数中最大值”的算法:①max=a,②输出max,③如果max<d,则max=d,④如果b〉max,则max=b,⑤输入a,b,c,d四个数,⑥如果c>max,则max=c。

正确的步骤序号为()A.⑤①④⑥③②B.⑤②④③⑥①C.⑤⑥③④①②D.⑤①④⑥②③答案:A5.已知直角三角形的两条直角边长分别为a,b.写出求斜边长c的算法如下:第一步,输入两直角边长a,b的值.第二步,计算c=错误!的值.第三步,________________.将算法补充完整,横线处应填____________________.答案:输出斜边长c的值6.已知一个学生的语文成绩为89,数学成绩为96,外语成绩为99,求他的总分和平均成绩的一个算法为:第一步,取A=89,B=96,C=99;第二步,_______________________________________________________;第三步,________________________________________________________;第四步,输出计算的结果.解析:应先计算总分D=A+B+C,然后再计算平均成绩E=错误!.答案:计算总分D=A+B+C计算平均成绩E=错误!7.求1×3×5×7×9×11的值的一个算法如下,请将其补充完整.1.求1×3得结果;2.将第1步所得结果3乘5,得到结果15.3.________________.4.再将第3步所得结果105乘9,得945.5.再将第4步所得结果945乘11,得到10 395,即为最后结果.解析:由于第2步是计算3×5,故第3步应是计算第3次乘法15×7。

算法导论第三版第二章第一节习题答案

算法导论第三版第二章第一节习题答案

算法导论第三版第⼆章第⼀节习题答案2.1-1:以图2-2为模型,说明INSERTION-SORT在数组A=<31,41,59,26,41,58>上的执⾏过程。

NewImage2.1-2:重写过程INSERTION-SORT,使之按⾮升序(⽽不是按⾮降序)排序。

注意,跟之前升序的写法只有⼀个地⽅不⼀样:NewImage2.1-3:考虑下⾯的查找问题:输⼊:⼀列数A=<a1,a2,…,an >和⼀个值v输出:下标i,使得v=A[i],或者当v不在A中出现时为NIL。

写出针对这个问题的现⾏查找的伪代码,它顺序地扫描整个序列以查找v。

利⽤循环不变式证明算法的正确性。

确保所给出的循环不变式满⾜三个必要的性质。

(2.1-3 Consider the searching problem:Input: A sequence of n numbers A D ha1; a2; : : : ;ani and a value _.Output: An index i such that _ D AOEi_ or the special value NIL if _ does not appear in A.Write pseudocode for linear search, which scans through the sequence, looking for _. Using a loop invariant, prove that your algorithm is correct. Make sure that your loop invariant fulfills the three necessary properties.)LINEAR-SEARCH(A,v)1 for i=1 to A.length2 if v = A[i]3 return i4 return NIL现⾏查找算法正确性的证明。

算法导论课程作业答案

算法导论课程作业答案

算法导论课程作业答案Introduction to AlgorithmsMassachusetts Institute of Technology 6.046J/18.410J Singapore-MIT Alliance SMA5503 Professors Erik Demaine,Lee Wee Sun,and Charles E.Leiserson Handout10Diagnostic Test SolutionsProblem1Consider the following pseudocode:R OUTINE(n)1if n=12then return13else return n+R OUTINE(n?1)(a)Give a one-sentence description of what R OUTINE(n)does.(Remember,don’t guess.) Solution:The routine gives the sum from1to n.(b)Give a precondition for the routine to work correctly.Solution:The value n must be greater than0;otherwise,the routine loops forever.(c)Give a one-sentence description of a faster implementation of the same routine. Solution:Return the value n(n+1)/2.Problem2Give a short(1–2-sentence)description of each of the following data structures:(a)FIFO queueSolution:A dynamic set where the element removed is always the one that has been in the set for the longest time.(b)Priority queueSolution:A dynamic set where each element has anassociated priority value.The element removed is the element with the highest(or lowest)priority.(c)Hash tableSolution:A dynamic set where the location of an element is computed using a function of the ele ment’s key.Problem3UsingΘ-notation,describe the worst-case running time of the best algorithm that you know for each of the following:(a)Finding an element in a sorted array.Solution:Θ(log n)(b)Finding an element in a sorted linked-list.Solution:Θ(n)(c)Inserting an element in a sorted array,once the position is found.Solution:Θ(n)(d)Inserting an element in a sorted linked-list,once the position is found.Solution:Θ(1)Problem4Describe an algorithm that locates the?rst occurrence of the largest element in a?nite list of integers,where the integers are not necessarily distinct.What is the worst-case running time of your algorithm?Solution:Idea is as follows:go through list,keeping track of the largest element found so far and its index.Update whenever necessary.Running time isΘ(n).Problem5How does the height h of a balanced binary search tree relate to the number of nodes n in the tree? Solution:h=O(lg n) Problem 6Does an undirected graph with 5vertices,each of degree 3,exist?If so,draw such a graph.If not,explain why no such graph exists.Solution:No such graph exists by the Handshaking Lemma.Every edge adds 2to the sum of the degrees.Consequently,the sum of the degrees must be even.Problem 7It is known that if a solution to Problem A exists,then a solution to Problem B exists also.(a)Professor Goldbach has just produced a 1,000-page proof that Problem A is unsolvable.If his proof turns out to be valid,can we conclude that Problem B is also unsolvable?Answer yes or no (or don’t know).Solution:No(b)Professor Wiles has just produced a 10,000-page proof that Problem B is unsolvable.If the proof turns out to be valid,can we conclude that problem A is unsolvable as well?Answer yes or no (or don’t know).Solution:YesProblem 8Consider the following statement:If 5points are placed anywhere on or inside a unit square,then there must exist two that are no more than √2/2units apart.Here are two attempts to prove this statement.Proof (a):Place 4of the points on the vertices of the square;that way they are maximally sepa-rated from one another.The 5th point must then lie within √2/2units of one of the other points,since the furthest from the corners it can be is the center,which is exactly √2/2units fromeach of the four corners.Proof (b):Partition the square into 4squares,each with a side of 1/2unit.If any two points areon or inside one of these smaller squares,the distance between these two points will be at most √2/2units.Since there are 5points and only 4squares,at least two points must fall on or inside one of the smaller squares,giving a set of points that are no more than √2/2apart.Which of the proofs are correct:(a),(b),both,or neither (or don’t know)?Solution:(b)onlyProblem9Give an inductive proof of the following statement:For every natural number n>3,we have n!>2n.Solution:Base case:True for n=4.Inductive step:Assume n!>2n.Then,multiplying both sides by(n+1),we get(n+1)n!> (n+1)2n>2?2n=2n+1.Problem10We want to line up6out of10children.Which of the following expresses the number of possible line-ups?(Circle the right answer.)(a)10!/6!(b)10!/4!(c) 106(d) 104 ·6!(e)None of the above(f)Don’t knowSolution:(b),(d)are both correctProblem11A deck of52cards is shuf?ed thoroughly.What is the probability that the4aces are all next to each other?(Circle theright answer.)(a)4!49!/52!(b)1/52!(c)4!/52!(d)4!48!/52!(e)None of the above(f)Don’t knowSolution:(a)Problem12The weather forecaster says that the probability of rain on Saturday is25%and that the probability of rain on Sunday is25%.Consider the following statement:The probability of rain during the weekend is50%.Which of the following best describes the validity of this statement?(a)If the two events(rain on Sat/rain on Sun)are independent,then we can add up the twoprobabilities,and the statement is true.Without independence,we can’t tell.(b)True,whether the two events are independent or not.(c)If the events are independent,the statement is false,because the the probability of no rainduring the weekend is9/16.If they are not independent,we can’t tell.(d)False,no matter what.(e)None of the above.(f)Don’t know.Solution:(c)Problem13A player throws darts at a target.On each trial,independentlyof the other trials,he hits the bull’s-eye with probability1/4.How many times should he throw so that his probability is75%of hitting the bull’s-eye at least once?(a)3(b)4(c)5(d)75%can’t be achieved.(e)Don’t know.Solution:(c),assuming that we want the probability to be≥0.75,not necessarily exactly0.75.Problem14Let X be an indicator random variable.Which of the following statements are true?(Circle all that apply.)(a)Pr{X=0}=Pr{X=1}=1/2(b)Pr{X=1}=E[X](c)E[X]=E[X2](d)E[X]=(E[X])2Solution:(b)and(c)only。

《算法导论(第二版)》(中文版)课后答案

《算法导论(第二版)》(中文版)课后答案

5
《算法导论(第二版) 》参考答案 do z←y 调用之前保存结果 y←INTERVAL-SEARCH-SUBTREE(y, i) 如果循环是由于y没有左子树,那我们返回y 否则我们返回z,这时意味着没有在z的左子树找到重叠区间 7 if y≠ nil[T] and i overlap int[y] 8 then return y 9 else return z 5 6 15.1-5 由 FASTEST-WAY 算法知:
15
lg n
2 lg n1 1 2cn 2 cn (n 2 ) 2 1
4.3-1 a) n2 b) n2lgn c) n3 4.3-4
2
《算法导论(第二版) 》参考答案 n2lg2n 7.1-2 (1)使用 P146 的 PARTION 函数可以得到 q=r 注意每循环一次 i 加 1,i 的初始值为 p 1 ,循环总共运行 (r 1) p 1次,最 终返回的 i 1 p 1 (r 1) p 1 1 r (2)由题目要求 q=(p+r)/2 可知,PARTITION 函数中的 i,j 变量应该在循环中同 时变化。 Partition(A, p, r) x = A[p]; i = p - 1; j = r + 1; while (TRUE) repeat j--; until A[j] <= x; repeat i++; until A[i] >= x; if (i < j) Swap(A, i, j); else return j; 7.3-2 (1)由 QuickSort 算法最坏情况分析得知:n 个元素每次都划 n-1 和 1 个,因 为是 p<r 的时候才调用,所以为Θ (n) (2)最好情况是每次都在最中间的位置分,所以递推式是: N(n)= 1+ 2*N(n/2) 不难得到:N(n) =Θ (n) 7.4-2 T(n)=2*T(n/2)+ Θ (n) 可以得到 T(n) =Θ (n lgn) 由 P46 Theorem3.1 可得:Ω (n lgn)

中科大算法导论第一,二次和第四次作业答案

中科大算法导论第一,二次和第四次作业答案
第一次作业
2.2-3 再次考虑线性查找问题 (见练习2.1-3)。在平均情况 下,需要检查输入序列中的多 少个元素?假定待查找的元素 是数组中任何一个元素的可能 性是相等的。在最坏情况下有 怎样呢?用Θ形式表示的话,线 性查找的平均情况和最坏情况 运行时间怎样?对你的答案加 以说明。 • 线性查找问题 • 输入:一列数A=<a1,a2,…,an>和一 个值v。 • 输出:下标i,使得v=A[i],或者当 v不在A中出现时为NIL。 • 平均情况下需要查找 (1+2+…+n)/n=(n+1)/2 • 最坏情况下即最后一个元素为待 查找元素,需要查找n个。 • 故平均情况和最坏情况的运行时 间都为Θ(n)。
• 2.3-2改写MERGE过程,使之不使 用哨兵元素,而是在一旦数组L或R 中的所有元素都被复制回数组A后, 就立即停止,再将另一个数组中 余下的元素复制回数组A中。 • MERGE(A,p,q,r) 1. n1←q-p+1 2. n2 ←r-q 3. create arrays L[1..n1] and R[1..n2] 4. for i ←1 to n1 5. do L*i+ ←A*p+i-1] 6. for j ←1 to n2 7. do R*j+ ←A*q+j+ 8. i ←1 9. j ←1
10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21.
k ←p while((i<=n1) and (j<=n2)) do if L[i]<=R[j] do A[k]=L[i] i++ else do A[k]=R[j] j++ k++ while(i<=n1) do A[k++]=L[i++] while(j<=n2) do A[k++]=R[j++]

《算法导论》习题答案

《算法导论》习题答案
i 1
n/2
n! nn , n! o(nn )
3.2.4 是否多项式有界 lg n !与 lg lg n !
设lgn=m,则 m! 2 m ( )m e2m ( )m em(ln m1) mln m1 nln ln n
∴lgn!不是多项式有界的。
T (n) O(lg n)
4.1.2 证明 T (n) 2T (n) n 的解为 O(n lg n)
设 T (n) c n lg n
T (n) 2c n lg n n c lg n n n c(n 1) lg(n / 2) n cn lg n c lg n cn n cn(lg n 1) n c(lg n 2n)
虽然用二分查找法可以将查找正确位置的时间复杂度降下来,但 是移位操作的复杂度并没有减少, 所以最坏情况下该算法的时间复杂 度依然是 (n2 )
2.3-7 给出一个算法, 使得其能在 (n lg n) 的时间内找出在一个 n 元
素的整数数组内,是否存在两个元素之和为 x
首先利用快速排序将数组排序,时间 (n lg n) ,然后再进行查找:
sin(n / 2) 2 1,所以 af (n / b) cf (n) 不满足。 2(sin n 2)
4.1.6 计算 T (n) 2T (
令 m lg n, T (2 ) 2T (2
m m/ 2
n ) 1 的解
) 1
令 T(n)=S(m),则 S (m) 2S (m / 2) 1 其解为 S (m) (m),T (n) S (m) (lg n)
4.2 The recursion-tree method 4.2.1 4.2.2 4.2.3 4.2.5 略

【第二章】算法竞赛入门经典(第二版)-课后习题答案

【第二章】算法竞赛入门经典(第二版)-课后习题答案

2-1 Daffodil2017年10月1日12:561 #include<stdio.h>2 int main(void)3 {4 int shui,xian,hua;5 int n =100;6 int g,s,b;7 int sum =0;8 while(n <1000)9 {10 g =n%10;11 s =n/10%10;12 b =n/100;13 shui =g*g*g;14 xian =s*s*s;15 hua =b*b*b;16 sum =shui +xian +hua;17 if(sum ==n)printf("%d\n",n);18 n++;19 }20 return0;21 }2-2 Hanxin2017年10月1日12:591 #include<stdio.h>2 int main(void)3 {4 int s,w,q;5 int kase =0;6 while(scanf("%d%d%d", &s, &w, &q) !=EOF)7 {8 int i =0;9 int n =10;10 while(n <=101)11 {12 if(n%3==s &&n%5==w &&n%7==q &&n <=100)13 {14 printf("Case %d: %d\n", ++kase,n);15 i =1;16 }17 else if(n >100&&i ==0)printf("Case %d: No answer\n", ++kase);18 n++;19 }20 }21 return0;22 }2-3 Triangle2017年10月1日12:591 #include <stdio.h>2 int main()3 {4 int i, j, n;5 scanf("%d", &n);6 for(i = 0; i < n; i++)7 {8 for(j= 0; j< I; j++)9 printf(" ");10 for(j= 0; j< 2*(n-i)-1; j++)11 printf("#\n");12 }13return0;14}2-4 Subsequence2017年10月1日13:001 #include<stdio.h>2 int main(void)3 {4 long long n,m;5 int kase =0;6 for( ; ; )7 {8 scanf("%lld%lld", &n, &m);9 if(n ==0&&m ==0)break;10 double sum =0.0;11 while(n <=m)12 {13 long long a =n*n;14 double b = (double)1.0/a;15 sum +=b;16 n++;17 }18 printf("Case %d: %.5lf\n", ++kase,sum);19 }20 return0;21 }22 /*23 将所有int改为long long方才解决问题,为什么?24 long long n, m; 为什么不能为int n, m; ?25 */2-5 Decimal2017年10月1日13:001 #include<stdio.h>2 int main(void)3 {4 int a,b,c;5 int kase =0;6 int i;7 for(;;)8 {9 scanf("%d%d%d", &a, &b, &c);10 if(a ==0&&b ==0&&c ==0)break;11 a %=b;12 printf("Case %d: %d.", ++kase,a/b);13 for(i =1;i <c;i++)14 {15 printf("%d",a*10/b);16 a =a*10%b;17 }18 if(a%b*10*10/b >=5)19 printf("%d\n",a%b*10/b+1);20 else21 printf("%d\n",a%b*10/b);22 }23 return0;24 }25 /*26 循环+判断 可以避开数组...27 求余的式子很巧妙...28 */2-6 Permutation2017年10月1日13:001 #include<stdio.h>2 int main(void)3 {4 int a,b,c,d,e,f,g,h,i;5 int n =100;6 while(n <=333)7 {8 a =n/100;9 b =n/10%10;10 c =n%10;11 if(a ==b ||a ==c ||b ==c )12 n++;13 else if(b ==0||c ==0)14 n++;15 else16 {17 int n2 =n*2;18 d =n2/100;19 e =n2/10%10;20 f =n2%10;21 if(e ==0||f ==0)22 n++;23 else if(d ==e ||d ==f ||e ==f)24 n++;25 else if(d ==b ||d ==c)// d == a省略,百位不会相等26 n++;27 else if(e ==a ||e ==b ||e ==c)28 n++;29 else if(f ==a ||f ==b ||f ==c)30 n++;31 else32 {33 int n3 =n*3;34 g =n3/100;35 h =n3/10%10;36 i =n3%10;37 if(h ==0||i ==0)38 n++;39 else if(g ==h ||g ==i ||h ==i)40 n++;41 else if(g ==b ||g ==c ||g ==e ||g ==f)42 n++;43 else if(h ==a ||h ==b ||h ==c ||h ==d ||h ==e ||h ==f)43 else if(h ==a ||h ==b ||h ==c ||h ==d ||h ==e ||h ==f)44 n++;45 else if(i ==a ||i ==b ||i ==c ||i ==d ||i ==e ||i ==f)46 n++;47 else48 {49 printf("%d %d %d\n",n,n2,n3);50 n++;51 }52 }53 }54 }55 return0;56 }Chapter 2 Q&A2017年10月1日13:001 #include<stdio.h>2 int main(void)3 {4 int n,i;5 scanf("%d", &n);6 for(i =1;i <=n;i++)7 printf("%d\n",i);89 /*10 for(i = 1; i <= n; i++)11 printf("%d\n", 2*i); //任务一1213 for(i = 2; i <= 2*n; i+=2) //任务二14 printf("%d\n", i);15 */1617 return0;18 }1 #include<stdio.h>2 int main(void)3 {4 double i;5 for(i =0;i !=10;i +=0.1)6 printf("%.1f\n",i);7 return0;8 }。

算法导论答案 (4)

算法导论答案 (4)

算法导论答案第一章:算法概述啊算法的定义算法是一系列解决问题的明确指令。

它是一个有穷步骤集,其中每个步骤或操作由确定性和可行性特征。

算法是通过将预期的输入转换为输出来解决问题的工具。

第二章:插入排序插入排序的思想插入排序是一种简单直观的排序算法,其基本思想是将待排序的序列分为已排序和未排序两部分,每次从未排序的部分中取出一个元素,并将其插入到已排序部分的正确位置,直到所有元素都被排序。

插入排序的算法实现以下是插入排序的伪代码:INSERTION-SORT(A)for j = 2 to A.lengthkey = A[j]// Insert A[j] into the sorted sequence A[1.. j-1].i = j - 1while i > 0 and A[i] > keyA[i + 1] = A[i]i = i - 1A[i + 1] = key插入排序的时间复杂度插入排序的时间复杂度为O(n^2),其中n是排序的元素个数。

虽然插入排序的最坏情况下的复杂度很高,但是对于小规模的数据集,插入排序是一种较快的排序算法。

第三章:分治策略分治策略的基本思想分治策略是一种解决问题的思想,它将问题的规模不断缩小,直到问题足够小而可以直接解决。

然后将子问题的解合并起来,得到原问题的解。

分治策略的应用实例一种经典的应用分治策略的算法是归并排序。

归并排序将待排序的序列划分为两个子序列,分别排序后再将两个有序子序列合并为一个有序序列。

以下是归并排序的伪代码:MERGE-SORT(A, p, r)if p < rq = floor((p + r) / 2)MERGE-SORT(A, p, q)MERGE-SORT(A, q + 1, r)MERGE(A, p, q, r)MERGE(A, p, q, r)n1 = q - p + 1n2 = r - qlet L[1..n1+1] and R[1..n2+1] be new arraysfor i = 1 to n1L[i] = A[p + i - 1]for j = 1 to n2R[j] = A[q + j]L[n1 + 1] = infinityR[n2 + 1] = infinityi = 1j = 1for k = p to rif L[i] <= R[j]A[k] = L[i]i = i + 1elseA[k] = R[j]j = j + 1分治策略的时间复杂度归并排序的时间复杂度为O(nlogn),其中n是待排序序列的长度。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

2.1-2 重写过程INSERTION-SORT,使之按非升序(而不是按非降序)排序。

伪代码如下:
INSERTION-SORT(A)
for j←to length[A]
do key←A[J]
i←j-1
while i>0 and A[i]<key
do A[i+1]←A[i]
i←i-1
A[i+1]←key
2.1-3 考虑下面的查找问题:
输入:一列数A=<a1,a2,…,an>和一个值V。

输出:下标i,使得V=A[i],或者当V不再A中出现时为NIL。

写出针对这个问题的线性查找的伪代码,它顺序地扫描整个序列以查找V。

利用循环不变式证明算法的正确性。

确保所给出的循环不变式满足三个必要的性质。

伪代码如下:
LINEAR-SEARCH(A,V)
flag←0
for i←1 to length[A]
do if A[i]==V
then print i
flag←1
if flag==0
then print NIL
循环不变式的证明如下:
初始化:首先,先来证明在第一轮迭代之前,它是成立的。

此时,flag初始化为0,表示未找到这样一个小标i,使得A[i]=V.若为1,则表示已找到一个或多个这样的下标。

那么,很显然,在还未开始之前flag=0是正确的,也就证明了循环不变式在循环的第一轮迭代开始之前是成立的。

保持:接下来证明每一轮循环都能使循环不变式保持成立。

我们看到,在第一个for循环体内,随着i逐个从1到遍历完整个数列的过程中,只要有一个下标i,使得A[i]等于V,那么在输出i的同时,将flag重新标记为1,表示已找到。

无论接下来是否还有这样满足条件的i出现,flag的值不变,仍为1,反之,若遍历完之后,没有找到这样的一个i,那么flag 在这个for循环中未做任何改变,仍为0。

所以,循环不变式的第二个性质也成立。

终止:对此线性查找算法来说,当i大于length[A]的值(即遍历完整个A数列后),for 循环结束。

这时,如果flag未改变(即flag=0),则说明未能找到这样的下标i,输出NIL;反之,若已在for循环中被修改为1,则不会运行此步语句,这也就意味着该算法是正确的。

2.1-4 有两个各存放在数组A和B中的n位二进制整数,考虑它们的相加问题。

两个整数的和以二进制形式存放在具有(n+1)个元素的数组C中。

请给出这个问题的形式化描述,并写出伪代码。

形式化描述如下:
首先,初始化数组C,使其n+1各元素的值都为0。

接着,利用for循环用i同时从n到1反向遍历A、B数组,每遍历一步,作一个判断:若A[i]+B[i]>1,则C[i]=C[i]+1;反之,C[i+1]=A[i]+B[i]。

最后,当i=0时,for循环结束,此时C数组中存储的即是所求的结果。

伪代码如下:
BINRARY-SUM(A,B,C)
for i←1 to n+1
do C[i]←0
for i←n to 1
do if A[i]+B[i]>1
then C[i]=C[i]+1
else C[i+1]=A[i]+B[i]
问题描述:
有两个各存放在数组A和B中的n位二进制整数,考虑它们的相加问题。

两个整数的和以二进制形式存放在具有(n+1)个元素的数组C中。

问题思考:
先假设整数的二进制数组中,高位在前,低位在后,所以得从后面往前面加——即从低位往高位的顺序加,即循环顺序应为从大到小(n到1)。

主要注意的一个问题就是进位的处理,当低位A[i]+B[i]>1时,就会向高位推送一个进位1,那么对于下一次的相加就应该有:
A[i-1]+B[i-1]+进位。

这里把进位描述为carry_flag,并将其初始化为0。

那么就有通用表达式:C[i+1]=(A[i]+B[i]+carry_flag)%2,
这里之所以对2取余,是因为二进制只有0,1(貌似这句话多余了);之所以是C[i+1],而不是C[i],是因为C[n+1](即整数的二进制表示的最低位)的值应该是(A[n]+B[n])%2 的结果,依次类推就有了上面的那个通用表达式,记得每次加完之后都要更新carry_flag。

伪代码:
BINARY-ADD(A,B,C,n)
▷这里假设整数的二进制表示中,高位在前,低位在后
carry_flag ← 0
for j ← n to 1
do key ← A[j]+B[j]+carry_flag
C[j+1] ← key mod 2
if key > 1
carry_flag ← 1
else
carry_flag ← 0
C[0] ← carry_flag
C/C++ 代码:
view sourceprint?
#include <stdio.h>
void binary_add(int* a, int *b, int *c, int length){
int i = 0;
int carry_flag = 0;
for(i=length-1; i>=0; i--){
int tmp = a[i]+b[i]+carry_flag;
c[i+1] = tmp % 2;
if(tmp>1){
carry_flag = 1;
}else{
carry_flag = 0;
}
}
c[0]=carry_flag;
}
void main(){
int i = 0;
int length = 0;
int A[8] = {1,0,1,1,1,0,0,1}; //185的二进制形式,高位在前,低位在后 int B[8] = {1,1,0,0,1,0,1,1}; //203的二进制形式,高位在前,低位在后 int C[9] = {0};
length = sizeof(A)/sizeof(int);
binary_add(A,B,C,length);
for(i=0;i<=length;i++){
printf("%d,",C[i]);
}
}
/*----------------------
* 输出结果为:
* 1,1,0,0,0,0,1,0,0
* 388的二进制表示形式
-------------------------*/
JAVA 代码:
view sourceprint?
public class Test{
int[] A = {1,0,1,1,1,0,0,1}; //185的二进制形式,高位在前,低位在后 int[] B = {1,1,0,0,1,0,1,1}; //203的二进制形式,高位在前,低位在后 int[] C = {0,0,0,0,0,0,0,0,0};
private void binary_add(int[] a, int[] b, int[] c, int length){ int carry_flag = 0;
for(int i=length-1; i>=0; i--){
int tmp = a[i]+b[i]+carry_flag;
c[i+1] = tmp % 2;
if(tmp>1){
carry_flag = 1;
}else{
carry_flag = 0;
}
}
c[0]=carry_flag;
}
public static void main(String[] args){
Test test = new Test();
test.binary_add(test.A, test.B, test.C, test.A.length); for(int i=0; i<=test.A.length; i++){
System.out.print(test.C[i]+",");
}
}
}
/*-----------------------
* 输出结果为:
* 1,1,0,0,0,0,1,0,0,
* 即十进制388
-------------------------*/。

相关文档
最新文档