Solution for exercise 1.1-4 in Introduction to Algorithms

来源:互联网 发布:c语言母牛生小牛代码 编辑:程序博客网 时间:2024/05/16 01:50

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.


/*
 * 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.
 */
int* addIntegers(int A[], int B[], int n) {
    int carry = 0;
    int* C = new int[n + 1];
    
    for (int i = 0; i < n; i++) {
        int sum = A[i] + B[i] + carry;

        carry = sum / 2;
        C[i] = sum % 2;
    }
    
    C[n] = carry;
    
    return C;
}
原创粉丝点击