#include <iostream>
#include <string>
using namespace std;
string _sub(string s1, string s2);
//比较两个正数的大小
inline int compareData(const string &s1,const string &s2)
{
if (s1.length()>s2.length()) return 1;
else if(s1.length()<s2.length()) return -1;
else return s1.compare(s2);
}
//相加
string _add(string s1, string s2)
{
if ('-' == s1[0])
{
//如果两个负数相加,换成两个正数相加,然后结果取负号
if ('-' == s2[0])
{
return "-" + _add(s1.erase(0,1),s2.erase(0,1));
}
//如果s1为负数,s2为正数,则为s2减s1的绝对值
else
{
return _sub(s2,s1.erase(0,1));
}
}
else
{
//如果s1为正数,s2为负数,则结果为s1减s2的绝对值
if ('-' == s2[0])
{
return _sub(s1,s2.erase(0,1));
}
//如果s1和s2都为正数,则相加
else
{
int flag = 0;//进位
//把俩整数高位加'0'对齐
int len1 = s1.length();
int len2 = s2.length();
if (len1 < len2)
{
for (int i=0;i < len2-len1;++i)
{
s1 = "0" + s1;
}
}
else if (len1 > len2)
{
for (int i=0;i<len1-len2;++i)
{
s2 = "0"+ s2;
}
}
string res;
int int1 = 0;
int int2 = 0;
for (int i=s1.length()-1; i>=0; --i)
{
int1 = s1[i]+s2[i]-2*'0'+int2;
res =char(int1%10 + '0') + res;
int2 = int1/10;
}
if (int2)
{
return "1"+res;
}
return res;
}
}
}
//相减
string _sub(string s1, string s2)
{
if ('-' == s2[0])
{
return _add(s1,s2.erase(0,1));
}
else
{
//s1为负数,s2为正数,相减结果为它们绝对值想加然后取负号
if ('-' == s1[0])
{
return '-'+_add(s1.erase(0,1),s2);
}
//s1与s2都为正数
else
{
//如果s1<s2,则返回s2-s1,然后取负号
if (compareData(s1,s2)<0)
{
return '-'+_sub(s2,s1);
}
//s1 == s2
else if(0 == compareData(s1,s2))
{
return 0;
}
//s1和s2都为正数,且s1>s2
else
{
string s1_copy = s1;
int miLen = s1_copy.length()-s2.length();
for (int i=s2.length()-1;i>=0;--i)
{
//如果s1的该位比s2小,则借位
if (s1_copy[i+miLen]<s2[i])
{
s1_copy[i+miLen] = char(s1[i+miLen]-s2[i]+10 +'0');
s1_copy[i+miLen-1] = s1[i+miLen-1] - 1;
}
else
{
s1_copy[i+miLen] = char(s1[i+miLen]-s2[i]+'0');
}
}
int i = miLen-1;
//如果最后还有借位
//s1>s2,如果i<0,则s1的长度和s2的长度相等,则最后肯定没有借位
//如果i=0,则表示s1比s2的长度大1
if(i == 0 && s1_copy[i]<'0')
{
s1_copy[i] = s1_copy[i] -1;
}
//如果i>0,则表示s1比s2的长度至少大于二
while (i>0 && s1_copy[i]<'0')
{
s1_copy[i] = char(s1[i]+10);
s1_copy[i-1] = s1[i-1]-1;
}
//去除结果中多余的前导0
s1_copy.erase(0,s1_copy.find_first_not_of('0'));
return s1_copy;
}
}
}
return "";
}
int main()
{
string s1 = "123456";
string s2 = "123459";
string s3 = "12345678";
string s4 = "123456";
string s5 = "-123456";
string s6 = "-123";
string s7 = "-12345678";
string s8 = "-123456";
/*cout<<s1<<'\t'<<s2<<'\t'<<compareData(s1,s2)<<endl;
cout<<s1<<'\t'<<s3<<'\t'<<compareData(s1,s3)<<endl;
cout<<s1<<'\t'<<s4<<'\t'<<compareData(s1,s4)<<endl;*/
/*cout<<s1<<'\t'<<s2<<'\t'<<_add(s1,s2)<<endl;
cout<<s5<<'\t'<<s6<<'\t'<<_add(s5,s6)<<endl;
cout<<s1<<'\t'<<s2<<'\t'<<_add("-989","-12")<<endl;*/
cout<<_sub("123","1245")<<endl;
return 0;
}
update 2016.06.27
相乘见我的另外一篇博客:相乘、