希望大家多多支持,算法导论2-1-4n位二进制相加源码,转载请注明出处。
问题描述:
-有两个各存放在数组A和B中的n位二进制整数,考虑它们的相加问题.两个整数的和以二进制形式存放在具有(n+1)个元素的数组C中
-There are stored in each of the two arrays A and B of the n-bit binary integers, the sum consider their problem two integers in binary form and stored in a (n+1) element array in C
#include<iostream>
#include<time.h>
using namespace std;
typedef int Elem;
void Show(Elem *A, int n)
{
for (int i = n; i >= 1; i--)
{
cout << A[i] ;
}
cout << endl;
}
//插入排序
void BINARY_ADD(Elem *A, int a,Elem *B,int b,Elem *C,int c)
{
int count = 0; //统计经过运行次数
Show(A, a);
Show(B, b);
Show(C, c);
cout << endl;
Elem flag=0,key=0;
int i = 1, j = 1;
//记录时间
clock_t start, finish;
double totaltime;
start = clock();
for (i = 1; i < a; i++)
{
key= A[i] + B[i] + flag;
C[i + 1] = key % 2;
if (key>1)
{
flag = 1;
}
count++;
Show(C,i);
}
if (flag == 1)
C[c] = 1;
//完成时间(秒)
finish = clock();
totaltime = (double)(finish - start) / CLOCKS_PER_SEC;
cout << "结果:";
Show(C, c);
cout << endl << "插入排序算法的运行次数为:" << count << endl;
cout << "插入排序算法的运行时间(秒)为:" << totaltime << endl << endl;
}
void main()
{
Elem A[7] = { 0, 1, 0, 1, 1, 1, 1 };
Elem B[7] = { 0, 1, 1, 1, 1, 1, 1 };
Elem C[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
BINARY_ADD(A, 6, B, 6, C, 7);
}