两个n位二进制数相加。两个整数存储在n元数组A和B。和按照二进制形式存储在n+1元数组C中。
#include<iostream>
using namespace std;
#define N 8
int main()
{
int a[N] = { 1, 1, 0, 1, 0, 1, 0, 1 };
int b[N] = { 0, 0, 0, 1, 1, 1, 1, 1 };
int carry = 0; //进位标志
int res[N + 1] = {0};
int i = 0;
for (int i = N - 1; i >= 0; i--)
{
res[i+1] = (a[i] + b[i] + carry) % 2;
carry = (a[i] + b[i] + carry) / 2;
}
res[i] = carry;
for (int i = 0 ; i <=N; i++)
{
cout << res[i];
}
cout << endl;
system("pause");
return 0;
}