3955 - A.回文数
小明最近对回文数比较感兴趣,所谓回文数,就是把一个数的数位反着写和原来的数相等,如若1234321就是一个回文数。小明发现如果对任选的一个正数n,不断加上把它反过来得到的数,经过若干步运算,有可能得到一个“回文数”,请你帮帮小明能否在指定步数m内对指定正数生成一个回文数。
如69经过4步可以变成一个回文数:
69 + 96 = 165
165 +561 = 726
726 + 627 = 1353
1353 + 3531 = 4884
题目输入
每一行第1个数是n(n<2^63),第2个数是m(m<10^5).
题目输出
如果n能在m步内生成回文,则输出yes,否则输出,no.
输入/输出样例
题目输入
67 1 69 5 69 3 11 1 99 1
题目输出
no yes no yes no
C++解答
#include <iostream> #include <string> #include <algorithm> #include<time.h> using namespace std; int main() { int m, n; char ch; string first, second, ans, next; int sum, bit, flag; while (cin >> first >> n) { ////clock_t start = clock(); flag = 0; m = n; while (n--) { second = first; reverse(second.begin(), second.end()); sum = 0; ans = ""; //ans.reserve(first.length() + 1); ans.resize(first.length()); size_t i = 0; for (i = 0; i < first.length(); i++) { bit = first[i] - '0' + second[i] - '0' + sum; sum = bit / 10; bit = bit % 10; ch = bit + '0'; ans[i] = ch; } if (sum >0) ans += char(sum + '0'); reverse(ans.begin(), ans.end()); first = ans; reverse(ans.begin(), ans.end()); if (first == ans) { flag = 1; break; } } ////clock_t end = clock(); if (flag == 1) { //cout << "yes" << ":" << first << ":" << m - n << "__sec:" << double(end - start) / CLOCKS_PER_SEC << endl; cout << "yes" << endl; } else { //cout << "no" << ":" << ans.length() << ":" << m << "__sec:" << double(end - start) / CLOCKS_PER_SEC << endl; cout << "no" << endl; } } return 0; }