您的位置:首页 > 其它

PAT 1024

2016-05-16 17:34 302 查看


1024. Palindromic Number (25)

时间限制

400 ms

内存限制

65536 kB

代码长度限制

16000 B

判题程序

Standard

作者

CHEN, Yue

A number that will be the same when it is written forwards or backwards is known as a Palindromic Number. For example, 1234321 is a palindromic number. All single digit numbers are palindromic numbers.

Non-palindromic numbers can be paired with palindromic ones via a series of operations. First, the non-palindromic number is reversed and the result is added to the original number. If the result is not a palindromic number, this is repeated until it gives
a palindromic number. For example, if we start from 67, we can obtain a palindromic number in 2 steps: 67 + 76 = 143, and 143 + 341 = 484.

Given any positive integer N, you are supposed to find its paired palindromic number and the number of steps taken to find it.

Input Specification:

Each input file contains one test case. Each case consists of two positive numbers N and K, where N (<= 1010) is the initial numer and K (<= 100) is the maximum number of steps. The numbers are separated by a space.

Output Specification:

For each test case, output two numbers, one in each line. The first number is the paired palindromic number of N, and the second number is the number of steps taken to find the palindromic number. If the palindromic number is not found after K steps, just output
the number obtained at the Kth step and K instead.

分析:考察字符串操作,如果想要偷懒的话,这题是没法ac的,因为把字符串转化成数字有长度限制,atof()等都不够,如果是反转一下,直接相加,在用sprintf()赋给字符串,最后只能拿13分;所以还是老老实实用字符串操作;

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdlib.h>
using namespace std;
char s[12],s1[12];
int str[12]={0};
int k;

bool panduan(char s[])
{
int l=strlen(s);
bool flag=true;
for(int i=0;i<l;i++)
{
if(s[i]!=s[l-i-1])
flag=false;
}
return flag;
}
int dieshu(char s[],int k)
{
bool flag=panduan(s);
int count=0;
while(!flag&&count<k)
{
char s2[12]={0};
int l=strlen(s);
strcpy(s2,s);
reverse(s2,s2+l);
int over=0;
for(int i=l-1;i>=0;i--)
{
over=0;
//s[i]=s[i]+s2[i]-'0';
int nu1=s[i]-'0';
int nu2=s2[i]-'0';
if(nu1+nu2>=10)
{
s[i]=s[i]+s2[i]-':';
over=1;
}
else s[i]=s[i]+s2[i]-'0';
if(i==0&&over==1)
{
for(int j=l-1;j>=0;j--)
{
s[j+1]=s[j];
if(j==0) s[j]='1';
}
}
else if(i!=0&&over==1)
{
s[i-1]=s[i-1]+over;
}
}
4000
flag=panduan(s);
count++;
}
return count;
}
int main()
{
memset(s,0,sizeof(s));
memset(s1,0,sizeof(s1));
cin>>s;
cin>>k;
int num=dieshu(s,k);
cout<<s<<endl;
cout<<num<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  PAT 1024