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.
My answers:
discriptions:
bitset <n> A; A[]=0 | 1;
bitset <n> B; B[] =0|1;
require:bitset<n+1> C= A+B; C[] = 0|1;
My codes in C++:
#include
<
iostream
>
#include < bitset >
using std::cin;
using std::cout;
using std::endl;
using std::bitset;
#define N 8
int main()
{
bitset<N+1> flag(0);
bitset<N> A;
bitset<N> B;
bitset<N+1> C;
cout << "enter two" << N << "bit binary" << endl;
cin >> A >> B;
for(int j=0; j != N; ++j)
{
if(A[j] && B[j] && flag[j])
{
C[j] = flag[j];
flag[j+1] = 1;
}
else if((A[j] && B[j]) || (A[j] && flag[j]) || (B[j] && flag[j]))
{
C[j] = 0;
flag[j+1] = 1;
}
else
C[j] = A[j] + B[j] + flag[j];
}
C[j] = flag[j];
cout << C << endl;
return 0;
}
#include < bitset >
using std::cin;
using std::cout;
using std::endl;
using std::bitset;
#define N 8
int main()
{
bitset<N+1> flag(0);
bitset<N> A;
bitset<N> B;
bitset<N+1> C;
cout << "enter two" << N << "bit binary" << endl;
cin >> A >> B;
for(int j=0; j != N; ++j)
{
if(A[j] && B[j] && flag[j])
{
C[j] = flag[j];
flag[j+1] = 1;
}
else if((A[j] && B[j]) || (A[j] && flag[j]) || (B[j] && flag[j]))
{
C[j] = 0;
flag[j+1] = 1;
}
else
C[j] = A[j] + B[j] + flag[j];
}
C[j] = flag[j];
cout << C << endl;
return 0;
}