高精度减法

• 清零
• 逆置
• 转换
• 相减计算（包含退位）

代码实现

逆置

``````//参数：需要逆置的数组，数组长度
void invertElem(char s[], size_t n)
{
size_t len = n-1;
for(size_t i=0,j=len;i<j;i++,j--)
{
char temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
``````

转换

``````//参数：数组，长度
void charInt(char s[], size_t n)
{
for(size_t i=0; i<n; i++)
s[i]-=48;
}
``````

相减

``````int main()
{
while(1)
{
char a[1024];
char b[1024];
char c[2049];

memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));

if(scanf("%s%s",a,b)==EOF) break;

size_t len_a = strlen(a);
size_t len_b = strlen(b);

size_t max_len = len_a>len_b?len_a:len_b;

invertElem(a,len_a);
invertElem(b,len_b);

charInt(a,len_a);
charInt(b,len_b);

//这部分是高精度减法的核心
int carry = 0;
for(size_t i=0; i<=max_len; i++)
{
c[i] = (a[i]-carry<b[i])?(10+a[i]-carry-b[i]):(a[i]-carry-b[i]);
carry = (a[i]-carry<b[i])?1:0;
}

int i;
for(i=max_len; i>=1&&c[i]==0; i--);

for(; i>=0; i--)
printf("%d", c[i]);
printf("\n");

}

return 0;
}
``````

完整代码

``````#include <bits/stdc++.h>

using namespace std;

//逆置
void invertElem(char s[], size_t n)
{
size_t len = n-1;
for(size_t i=0,j=len;i<j;i++,j--)
{
char temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}

//转换
void charInt(char s[], size_t n)
{
for(size_t i=0; i<n; i++)
s[i]-=48;
}

int main()
{
while(1)
{
char a[1024];
char b[1024];
char c[2049];

memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));

if(scanf("%s%s",a,b)==EOF) break;

size_t len_a = strlen(a);
size_t len_b = strlen(b);

size_t max_len = len_a>len_b?len_a:len_b;

invertElem(a,len_a);
invertElem(b,len_b);

charInt(a,len_a);
charInt(b,len_b);

//这部分是高精度减法的核心
int carry = 0;
for(size_t i=0; i<=max_len; i++)
{
c[i] = (a[i]-carry<b[i])?(10+a[i]-carry-b[i]):(a[i]-carry-b[i]);
carry = (a[i]-carry<b[i])?1:0;
}

int i;
for(i=max_len; i>=1&&c[i]==0; i--);

for(; i>=0; i--)
printf("%d", c[i]);
printf("\n");

}

return 0;
}
``````