PAT乙级 1079. 延迟的回文数 (20)

#include <iostream>
using namespace std;
int n;//数的长度有在加的过程中变化 

bool isPalindrome(int a[]){//判断是否是回文数 
	int mid = 0;
	if(n%2 == 0)
	{
		mid = n/2-1;
		for(int i = 0, j = n-1; i <= mid && j >= mid+1; i++, j--)
			if(a[i] != a[j])
				return 0;
	}	
	else
	{
		mid = n/2;
		for(int i = 0, j = n-1; i < mid && j > mid; i++, j--)
			if(a[i] != a[j])
				return 0;
	}	
	return 1;
}

void adverse(int a[], int adv[]){//倒序 
	int k = 0;
	for(int i = n-1; i >= 0; i--)
		adv[k++] = a[i];
}

void add(int a[], int adv[]){//大数相加 
	int temp1[1010] = {0};
	int temp2[1010] = {0};
	int i = 0;
	while(i < n || a[i] != 0)
	{	
		int up = (a[i]+adv[i])/10;
		int now = (a[i]+adv[i])%10;
		temp1[i++] = now;
		a[i] += up;
	}
	n = i;
	adverse(temp1, temp2);
	for(int j = 0; j < i; j++)
		a[j] = temp2[j];
}

int main(){
	string b;
	cin >> b;
	int a[1005] = {0};
	int adv[1005] = {0};
	for(int i = 0; i < b.length(); i++)
		a[i] = b[i] - '0';
	n = b.length();
	int count = 0;
	while(!isPalindrome(a))	
	{
		count++; 
		if(count == 11)
			break;
		adverse(a, adv);
		for(int i = 0; i < n; i++)
			cout << a[i];
		cout << " + ";
		for(int i = 0; i < n; i++)
			cout << adv[i];
		add(a, adv);
		cout << " = "; 
		for(int i = 0; i < n; i++)
			cout << a[i];
		cout << endl;	
	}
	if(count == 11)
		cout << "Not found in 10 iterations." << endl;
	else
	{
		for(int i = 0; i < n; i++)
			cout << a[i];
		cout << " is a palindromic number." << endl;
	} 
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37430374/article/details/78816184