PAT 1024. Palindromic Number

回文反转相加


之前做过一次,部分错误。

今天重做,发现是

		ret.push_back( (num[i] + other[i] - 96 + carry) % 10 + 48);
		carry = (num[i] + other[i] - 96 + carry) / 10; // carry之前忘记加了
在for循环计算carry时,先前的carry忘记加了。

如果按照点击打开链接中,

		sum = s[i]+rev[i]-'0'-'0'+carry;
		res.insert(res.begin(),sum%10+'0');
		carry = sum/10;
写成这样的形式,错的几率就小一些了 


代码:

#include <iostream>
#include <sstream>
#include <list>
#include <deque>
#include <algorithm>

using namespace std;

string number;
int k;

string change_number(string num)
{
	string ret;

	string other = num;
	reverse(other.begin(), other.end());
	int carry = 0; 
	for (size_t i = 0; i < num.size(); ++ i)
	{
		ret.push_back( (num[i] + other[i] - 96 + carry) % 10 + 48);
		carry = (num[i] + other[i] - 96 + carry) / 10; // carry之前忘记加了
	}
	if (carry == 1)
	{
		ret.push_back('1');
	}
	reverse( ret.begin(), ret.end() );	

	return ret;
}

bool palindromic()
{
	string tmp = number;
	reverse(tmp.begin(), tmp.end());
	return tmp == number;
}

int main()
{
	cin >> number >> k;

	int i;
	for (i = 0; i < k; ++ i)
	{
		if ( palindromic() )	
		{
			break;
		}
		number = change_number(number);
//		cout << number << endl;
	}
	cout << number << endl;
	cout << i << endl;

	system("pause");
	return 0;
}


你可能感兴趣的:(pat,Palindromic)