您的位置:首页 > 编程语言 > Go语言

Introduction to Algorithms:exercise2.1_4

2007-09-26 21:19 435 查看
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;






}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: