1024. Palindromic Number (25)

来源:互联网 发布:linux 内核 网络库 编辑:程序博客网 时间:2024/06/07 14:39

将一个数字倒转并且相加,多次重复后可能生成一个回文数,题目要求在一定的次数内算出、或者算不出回文数。
很简单的题目。但是由于N <= 10^6 K<=100,这里需要使用字符串表示数字
倒转数字非常简单,相加的主要思路是,如果按照顺序把最低位的顺序相加放到最低位,最高位数字相加到最高位的话,可能最后会发现缺少了一个位置保存最高位的进位,于是使用倒转相加的方式,最低位放在结果的最前面,最高位放在结果的最后面。
注意reverse函数在algonithm里面

/*1024. Palindromic Number (25)时间限制400 ms内存限制65536 kB代码长度限制16000 B判题程序Standard作者CHEN, YueA 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.Sample Input 1:67 3Sample Output 1:4842Sample Input 2:69 3Sample Output 2:13533Given any positive integer N, you are supposed to find its paired palindromic number and the number of steps taken to find it.If the palindromic number is not found after K steps, just output the number obtained at the Kth step and K instead.*/#include<iostream>#include<algorithm>#include<string>using namespace std;inline bool isPalindromic(const string&tmp){return string(tmp.rbegin(),tmp.rend())== tmp;}string DealIt(const string _base){    string radd;    auto i = _base.begin();    auto j = _base.rbegin();    char t = 0;//进位与否    for(;i < _base.end();i++,j++){        char tmp = (*i + *j + t - '0' - '0');        radd.push_back(tmp%10 + '0');        t = tmp/10;    }    if(t == 1)radd.push_back('1');    reverse(radd.begin(),radd.end());    return radd;}int main(void){    string base;    int maxstep,i;    cin >> base >> maxstep;    for(i = 0;i < maxstep&&!isPalindromic(base);i++)        base = DealIt(base);    cout << base << endl << i;    return 0;}

写完后思考是好习惯!
这种大数字的表示方式无疑是非常浪费空间的,如果在做东西的过程之中遇到了相同的问题,可以选择使用每个字节表示两位十进制数(或者说一位一百进制数)的方式,如果需要使用十进制表示的话,可以考虑使用每个字节表示两位16进制数的方式(或者说是一位256进制数的方式);
考虑到计算过程中最高位不确定,为了内存管理的方便,可以考虑倒转表示数字 ,比如说 数字13132在内部表示为23131,这样可以在计算的时候更方便表示最高位

0 0