• 【无标题】


    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.

    Sample Input 1:

    67 3
    

    Sample Output 1:

    1. 484
    2. 2

    Sample Input 2:

    69 3
    

    Sample Output 2:

    1. 1353
    2. 3

    题意分析:

    由于不断的翻转相加,最后变成了大整数运算,会溢出,所以转换为string字符串类型来计算,主要用到了reverse()函数来处理字符串的翻转,注意这个大整数相加函数add()的写法

    代码如下:

    1. #include
    2. using namespace std;
    3. string s;
    4. bool isPalindromic(string s)
    5. {
    6. string s2 = s;
    7. reverse(s.begin(), s.end());
    8. return s2==s;
    9. }
    10. void add(string t) {
    11. int len = s.length(), carry = 0;
    12. for (int i = 0; i < len; i++) {
    13. s[i] = s[i] + t[i] + carry - '0';
    14. carry = 0;
    15. if (s[i] > '9') {
    16. s[i] = s[i] - 10;
    17. carry = 1;
    18. }
    19. }
    20. if (carry) s += '1';
    21. reverse(s.begin(), s.end());
    22. }
    23. int main()
    24. {
    25. int k;
    26. cin >> s >> k;
    27. int step = 0;
    28. while (step <= k)
    29. {
    30. if (isPalindromic(s)) {
    31. cout << s << "\n" << step << endl;
    32. return 0;
    33. }
    34. if (step == k)break;
    35. string right = s;
    36. reverse(right.begin(), right.end());
    37. add(right);
    38. step++;
    39. }
    40. cout << s << "\n" << k << endl;
    41. return 0;
    42. }

    运行结果如下:

  • 相关阅读:
    Acwing 838. 堆排序
    使用AVX2指令集加速推荐系统MMR层余弦相似度计算
    [ 云计算 | AWS ] AI 编程助手新势力 Amazon CodeWhisperer:优势功能及实用技巧
    使用Vite快速构建Vue3+ts+pinia脚手架
    Oracle 踩坑记录
    微信、支付宝、百度、抖音开放平台第三方代小程序开发总结
    计算机硬件基本组成和各硬件工作原理
    【香橙派4B】6、测试串口
    Spring Boot:控制器调用模板引擎渲染数据的基本过程
    Android进程与线程
  • 原文地址:https://blog.csdn.net/qq_47677800/article/details/126024217