luogu1480 A/B Problem(高/低)

luogu1480  A/B Problem

时空限制    1000ms/128MB

题目描述

        输入两个整数a,b,输出它们的商(a<=10^5000,1<=b<=10^9)。

输入

        两行,第一行是被除数,第二行是除数。

输出

        一行,商的整数部分

输入样例

10
2

输出样例

5

代码

法一:数组模拟

#include<iostream>
#include<string>
#include<cstring>
using namespace std;
const int N = 5005;
int a[N],b,c[N];

void zhuan(string s,int a[]){
	memset(a,0,sizeof(int)*N);
	a[0] = s.size();
	for (int i=1; i<=a[0]; ++i) a[i]=s[a[0]-i]-48;
}

void div(int a[],int b,int c[]){
	memset(c,0,sizeof(int)*N);
	c[0] = a[0];
	long long r=0;	//b在极限会越界,用longlong
	for (int i=c[0]; i>=1; --i){
		r = 10*r+a[i];
		c[i] = r/b;
		r %= b;
	}
	while (c[c[0]]==0 && c[0]>1) --c[0];
}

void output(int a[]){
	for (int i=a[0]; i>=1; --i) cout<<a[i];
	cout<<'\n';
}

int main(){
	string s;
	while (cin>>s>>b){
		zhuan(s,a);
		div(a,b,c);
		output(c);
	}
	return 0;
}

法二:重载运算符

#include<iostream>
#include<cstring>
#include<string>
using namespace std;
const int N = 5005;
struct bign{
	int len,d[N];
	bign(){ memset(d,0,sizeof(d)); len=1; }	//构造函数,默认初始化
	bign(string x){							//构造函数,string初始化
		memset(d,0,sizeof(d));
		len = x.size();
		for (int i=1; i<=len; ++i) d[i]=x[len-i]-48;
	}
	void clear0(){	//成员函数  清掉高位0,保证至少1位
		while (d[len]==0 && len>1) --len;
	}
	bign operator / (const int &b){			//重载/ 高/低
		bign c;		//c=结构体本身/b
		c.len = len;
		long long r=0;	//b在极限会越界,用longlong
		for (int i=len; i>=1; --i){
			r = 10*r+d[i];
			c.d[i] = r/b;
			r %= b;
		}
		c.clear0();
		return c;
	}
	friend istream& operator >> (istream& input,bign &x){	//重载输入流
		string s;
		input>>s;
		x = s;
		return input;
	}
	friend ostream& operator << (ostream& output,const bign &x){//重载输出流
		for (int i=x.len; i>=1; --i) cout<<x.d[i];
		return output;
	}
};

int main(){
	bign a; int b;
	while (cin>>a>>b)		//需重载输入流
		cout<<a/b<<'\n';	//需重载输出流、高/低
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值