1024. Palindromic Number (25)

本文介绍了一种用于检查字符串是否为回文的方法,并提供了一个通过反复合成直到形成回文的算法实现。该算法适用于任意长度的字符串,通过逐位相加原始字符串与其反转后的字符串来生成新的字符串,直至新字符串成为回文为止。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <map>
using namespace std;

bool judge(string s){
    string st = s;
    reverse(st.begin(), st.end());
    if(st == s) return true;
    else return false;
}

void add(string &s){
    string st = s;
    reverse(st.begin(), st.end());
    int c = 0;
    for (int i = (int)st.size() - 1; i >= 0; i--) {
        s[i] = s[i] + st[i] + c - '0';
        if(s[i] > '9'){
            s[i] = s[i] - 10;
            c = 1;
        }else c = 0;
        if((i == 0) && c == 1){
            s = "1" + s;
        }
    }
}

int main(){
    int k;
    string s, st;
    cin >> s >> k;
    if(judge(s)){
        cout << s << 0 << endl;
        return 0;
    }
    for (int i = 1; i <= k; i++) {
        add(s);
        if (judge(s)) {
            cout << s << endl << i << endl;
            return 0;
        }
    }
    cout << s << endl << k << endl;

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值