• 【无标题】


    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. }

    运行结果如下:

  • 相关阅读:
    深入剖析Sgementation fault原理
    android动画的学习与总结
    17 | DataSource 为何物?加载过程是怎样的
    Mac系统下Gauge初体验
    【K8S专栏】Kubernetes工作负载管理
    Cholesterol-PEG-NHS,NHS-PEG-CLS,胆固醇-聚乙二醇-活性酯修饰小分子材料
    《C++程序设计原理与实践》笔记 第2章 Hello, World!
    ElementUI浅尝辄止23:Loading 加载
    SSH远程访问开发板
    JavaScript常用工具函数
  • 原文地址:https://blog.csdn.net/qq_47677800/article/details/126024217