您的位置:首页 > 其它

大数减法

2009-06-19 10:09 357 查看
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>
#include <string>
#include <algorithm>

//using namespace std;

std::ifstream cin("in.txt");
std::ofstream cout("out.txt");

std::string sub;

std::string big_sub(std::string a,std::string b)
{
//a-b
std::string result = "";
int op = 0;

bool flag = true;

if (a == b)
{
return "0";
}

int Length = 0;
int aLength = a.length();
int bLength = b.length();

if (aLength<bLength)
{
for (int i = 0; i<bLength - aLength; i++)
{
a = "0"+a;
}
Length = bLength;
}
else
{
for (int i = 0; i<aLength - bLength; i++)
{
b = "0"+b;
}
Length = aLength;
}

if (a<b)
{
std::swap(a,b);
flag = false;
}

for (int i =Length-1;i>=0;i--)
{
int t = 0;

t = a[i] - b[i]+ op;

if (t<0)
{
t = t+10;
op = -1;
}
if (i>0||t)
{
result += ('0'+t);
}

}

std::reverse(result.begin(),result.end());

if (!flag)
{
result ="-"+result;
}

return result;
}

int main(int argc, char* argv[])
{

std::string a,b;
while (cin>>a>>b)
{
cout<<big_sub(a,b)<<"/n";
}

return 0;
}

Input:
87
10000
0
0
00000000
1

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