自己写的高精度减法的代码,复制到OJ能过,但是本地DEVC++运行一直没有结果输出,改用在线IDE提示超时,死活找不到原因。 求大神指点原因
#include <bits/stdc++.h> // 万能头文件
using namespace std;
const int N=10+1e5;
string SUBTRACT(string s1,string s2)
{
// 输入两个数字求差
string ans;
bool flag=true;
int lsta[N], lstb[N], balance[N];
memset(lsta,0,sizeof(lsta));
memset(lstb,0,sizeof(lstb));
memset(balance,0,sizeof(balance));
cin >> s1 >> s2;
// size()计算字符串有效长度(不包括'\0')
int L1 = s1.size();
int L2 = s2.size();
// 第一个数比第二个数小的时候,需要交换两数位置
// ①第一个数比第二个数长度短
// ②第一个数和第二个数一样长,数值比第二个数少(string类型的比较是按位比较ASCII码)
// 字符串放进整型数组中,整型数组中,低下标存放的是字符串高下标(数字低位)
for(int i = 0; i < L1; i++) lsta[i] = s1[L1 - 1 - i] - '0';
for(int i = 0; i < L2; i++) lstb[i] = s2[L2 - 1 - i] - '0';
// 减法运算
for(int i = 0; i < L1; i++)
{
if(lsta[i] < lstb[i])
{ // 如果当前数位不够减,需要发生借位
lsta[i + 1]--;
balance[i] = lsta[i] + 10 - lstb[i];
}
else
{
balance[i] = lsta[i] - lstb[i];
}
}
// 去掉结果中的前导零
int k = L1--;
while(balance[k] == 0 and k > 0)
{
k--;
}
// 数字转为字符
for(int i=k;i>=0;i--)
{
ans+=balance[i]+'0';
}
if (!flag)
{
ans="-"+ans;
}
return ans;
}
int main()
{
string a,b;
cin>>a;
cin>>b;
cout<<SUBTRACT(a,b)<<endl;
return 0;
}