高精度减法(数组模拟)

大整数减法模板如下:

#include <iostream>
#include <cstring>
#include <cctype>

#define SIZE 1001

using namespace std;

bool neg; // 是否为负数
int a[SIZE], b[SIZE], temp[SIZE];

int comp(int a[], int b[]) // 判断大小,a > / = / < b 的情况下,返回值为 1 / 0 / -1
{
	int i, la = a[0], lb = b[0];
	
	if (la > lb)
	{
		return 1;
	}
	if (la < lb)
	{
		return -1;
	}
	for (i = la; i > 0; --i)
	{
		if (a[i] > b[i])
		{
			return 1;
		}
		if (a[i] < b[i])
		{
			return -1;
		}
	}
	
	return 0;
}

void _swap(int *a, int *b) // 交换两个数组
{
	int i, len = max(a[0], b[0]);
	
	for (i = 0; i <= len; ++i)
	{
		swap(a[i], b[i]);
	}
	
	return;
}

void sub(int a[], int b[]) // 高精度减法,a -= b
{
	int i, carry = 0, len;
	
	neg = false;
	if (comp(a, b) == -1)
	{
		neg = true; // 结果为负数
		_swap(a, b);
	}
	len = a[0];
	for (i = 1; i <= len; ++i) // 按位相减
	{
		a[i] -= b[i] + carry;
		if (a[i] < 0)
		{
			a[i] += 10; // 处理借位情况
			carry = 1;
		}
		else
		{
			carry = 0;
		}
	}
	
	return;
}

void read(int a[]) // 读入大整数
{
	char ch = 'a';
	int i;
	
	while (!isdigit(ch))
	{
		ch = getchar();
	}
	while (isdigit(ch))
	{
		temp[++a[0]] = ch - '0'; // 大概是快读的思想
		ch = getchar();
	}
	for (i = 1; i <= a[0]; ++i)
	{
		a[i] = temp[a[0]-i+1];
	}
	
	return;
}

void write(int a[]) // 输出大整数
{
	int len = a[0] + 1;
	
	if (neg) // 如果是负数
	{
		putchar('-'); // 就输出负号'-'
	}
	while (--len)
	{
		putchar(a[len] + '0'); // 按位输出
	}
	
	return;
}

int main(int argc, char** argv)
{
	read(a);
	read(b);
	
	sub(a, b);
	
	write(a);
	
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值