binary addition


/*============================================================================
 Name        : Exercise.cpp
 Author      : Haier
 Version     : 1.01
 Copyright   : Copyright (c) 2014
 Description : binary addition  in C++, Ansi-style, Compile by Eclipse
 ============================================================================*/
#include <iostream>
#include <stack>
#include <stdio.h>

using namespace std;

stack<int> read()
{
    stack<int> MyStack;
    int Number,Bit,i;

    cout<<"Please input the Bit: ";
    cin>>Number;
    cout<<"Please input the Number of each Bit: ";

    for(i=0; i<Number; i++)
    {
        cin>>Bit;
        MyStack.push(Bit);
    }

    return MyStack;
}

void display(stack<int> &MyStack)
{
    while(!MyStack.empty())
    {
        cout<<" "<<MyStack.top();
        MyStack.pop();
    }
}

stack<int> add(stack<int> &stack1,stack<int> &stack2)
{
    int PlusNumber=0,Addend=0;
    int Sum=0,Carry=0;
    stack<int> Mystack;

    while(!stack1.empty() || !stack2.empty())
    {
        if(!stack1.empty())
        {
            PlusNumber=stack1.top();
            stack1.pop();
        }

        if(!stack2.empty())
        {
            Addend=stack2.top();
            stack2.pop();
        }

        Sum  =(PlusNumber+Addend+Carry)%2;
        Carry=(PlusNumber+Addend+Carry)/2;
        Mystack.push(Sum);
    }

    if(Carry==1)
    {
        Mystack.push(Carry);
    }

    return Mystack;
}

int main()
{
	stack<int> s1,s2,s3;
	int ch;

	cout<<"\n\t\t\t***MENU***\n";
	cout<<"\n1........Read first number"
	    <<"\n2........Read second number"
	    <<"\n3........Display addtion of two numbers"
	    <<"\n4........Exit";

	do
	{
		cout<<"\nEnter your choice..: ";
		cin>>ch;

		switch(ch)
		{
		case 1:
		    fflush(stdin);
			s1=read();
			break;

		case 2:
		    fflush(stdin);
			s2=read();
			break;

		case 3:
			cout<<"\nThe result of addition is :";
			s3=add(s1,s2);
			display(s3);
			break;
		}
	}while(ch!=4);
	
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值