exercises2.1-4 of introduction to Algorithms

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 the an (n+1) -element array C. State the problem formally and write pseudocode for adding the two integers.

[Pseudocode]

Adding-A-B(A,B,C)
     key = 0
     for i = 1 to n
          sum = A[i] + B[i] +key
          C[i] = sum % 2
          key = sum / 2
      C[n+1] = key

[C++ Code]

void ex_2_1_4(int A[],int b[],int C[],int n)
{
    int key = 0;
    int sum = 0;
    for (int i=0;i<n;i++)
    {
        sum = A[i] + b[i] + key;
        C[i] = sum % 2;
        key = sum / 2;
    }
    C[i] =  key;
}

 

posted @ 2013-01-13 17:07  理想空间  阅读(472)  评论(0编辑  收藏  举报