试题 算法训练 Yaroslav and Algorithm

主要考察大数运算

#include 
#include
#include
#include
using namespace std;
char numTable[] = { '0','1','2','3','4','5','6','7','8','9' };
const int maxn = 100;
string NumToStr(int n);
struct bigNum
{
	int n,data[maxn];
	bigNum()
	{
		memset(data, 0, sizeof(data));
	}
};
void showBigNum(bigNum& num);
bigNum StrToBigNum(string& num);
string BigNumToStr(bigNum& num);
bigNum BigNumPlus(bigNum n1,bigNum n2);
string PlusConvert(string s);
int main()
{
	int n;
	cin >> n;
	getchar();
	string* str_set = new string[n];
	for (int i = 0; i < n; i++)getline(cin, str_set[i]);
	vector<string>res;
	for (int i = 0; i < n; i++)
	{
		string cur_str = str_set[i] + "<>" + PlusConvert(str_set[i]);
		res.push_back(cur_str);
	}
	for (int i = 0; i < n; i++)
	{
		if (i != n - 1)cout << res[i] << endl;
		else cout << res[i];
	}
}
string PlusConvert(string s)
{
	bigNum bn = StrToBigNum(s);
	bigNum yi;
	yi.n = 1;
	yi.data[0] = 1;
	bigNum aa = BigNumPlus(bn, yi);
	string res = BigNumToStr(aa);
	return res;
}
bigNum StrToBigNum(string&num)
{
	bigNum res;
	int len = num.length();
	res.n = len;
	for (int i = 0; i < len; i++)
	{
		res.data[len-i-1] = num[i]-48;
	}
	return res;
}
string BigNumToStr(bigNum&num)
{
	string res="";
	for (int i = num.n - 1; i >= 0; i--)
	{
		res += numTable[num.data[i]];
	}
	return res;
}
bigNum BigNumPlus(bigNum n1,bigNum n2)
{
	bigNum res;
	int i, carry = 0;
	for (i = 0; i < n1.n || i < n2.n; i++)
	{
		int cur_sum = n1.data[i] + n2.data[i] + carry;
		res.data[i] = cur_sum % 10;
		carry = cur_sum / 10;
	}
	if (carry != 0)
	{
		res.data[i] = carry;
		res.n = i + 1;
	}
	else res.n = i;
	return res;
}
string NumToStr(int n)
{
	string res = "";
	while (n)
	{
		int c = n % 10;
		res = numTable[c] + res;
		n /= 10;
	}
	return res;
}
void showBigNum(bigNum& num)
{
	for (int i = num.n - 1; i >= 0; i--)cout << num.data[i];
}

你可能感兴趣的:(试题 算法训练 Yaroslav and Algorithm)