您的位置:首页 > 其它

POJ2602《Superlong sums》方法:高精度 模拟

2013-02-25 10:15 281 查看
题目比较拗口的大数相加,两个数居然分开一个数字一个数字读入,注意要用scanf()读入,cin因为重载,没有指定格式,输入比较耗时。同时输出也要先转换为字符串形式,不然循环输出整数数组会超时。

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

int n; // 输入长度

int main()
{
	//freopen("temp.txt", "r", stdin);
	cin >> n;
	int *a = new int
;
	int *b = new int
;
	int *ans = new int
;
	char *ansc = new char[n+1];
	for (int i = n-1; i >= 0; --i) 
		scanf("%d %d", &a[i], &b[i]);
	
	memset(ans, 0, sizeof(ans) * n);  //当ans为int ans
时,用sizeof是不同的
	int carry = 0;
	for (int i = 0; i < n; ++i) { //这题居然结果与输入结果长度一致
		ans[i] += a[i] + b[i] + carry;
		carry = ans[i] / 10;
		ans[i] = ans[i] % 10;
	}
	for (int i = 0; i < n; ++i)   // 这里不能直接循环输出ans,会超时
		ansc[i] = ans[n-1-i] + '0';
	ansc
 = '\0';
	cout << ansc << endl;

	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: