关闭

Introduction to Algorithms:exercise2.1_4

505人阅读 评论(0) 收藏 举报

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;

        
}
 
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:251410次
    • 积分:3446
    • 等级:
    • 排名:第9665名
    • 原创:82篇
    • 转载:49篇
    • 译文:2篇
    • 评论:47条
    最新评论