PAT甲级1024 【Palindromic Number (25)】【字符串反转+模拟加法】

本文介绍了一种解决特定字符串问题的方法,通过字符串反转及加法运算实现回文数判断。针对大数值运算,采用字符串替代传统数值类型,避免了数据溢出问题,并提供了完整的代码实现。

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

题目链接
分析:简单字符串反转,再加上加法计算,一开始用long long有两个测试点没过TAT。。估计是范围爆了10^10迭代相加100次,据大神说是10^40数量级,因此改用字符串进行加法操作。

补充:2018.8.11更新,博主再次倒在了数据范围上(可恶呀),后来测出了数据超出long long,改用字符串过。

更新代码:

#include<cstdio>
#include<algorithm>
#include<iostream>
using namespace std;
string convert(string num1){
    int len = num1.length(), c = 0; 
    string num2 = num1, res = "";
    reverse(num2.begin(), num2.end());
    for(int i = 0; i<len; i++){
        int tem = num1[i]+num2[i]-'0'-'0'+c;
        c = tem/10;
        res += tem%10+'0';
    }
    if(c) res += c+'0';
    reverse(res.begin(), res.end());
    return res;
}
int isPalindromic(string num){
    int len = num.length();
    for(int i = 0; i<len/2; i++)
        if(num[i] != num[len-i-1]) return 0;
    return 1;
}
int main(){
    //freopen("aa.txt", "r", stdin);
    string num;
    int i, k;
    cin >> num >> k;
    for(i = 0; i<k; i++){
        if(isPalindromic(num)) break;
        num = convert(num);
    } 
    cout << num << "\n" << i ;

    return 0;
}

代码

#include<bits/stdc++.h>
using namespace std;
bool isP(string tem){
    for(int i = 0; i<tem.length()/2; i++){
        if(tem[i] != tem[tem.length()-1-i]) return false;
    }
    return true;
}
string add(string a, string b){
    string res="";
    int c = 0,i=0;
    for(i = 0; i<a.length(); i++){
        int tem = a[i]+b[i]-'0'-'0'+c;
        c = tem/10;
        res += tem-c*10+'0';
    } 
    if(c != 0) res+=c+'0';
    reverse(res.begin(), res.end());
    return res;
}
int main(){
    long long k,cnt=0;
    string a,b,res;
    cin>>res>>k;    
    while(cnt < k && !isP(res)){
        a = res;
        b = a;
        reverse(b.begin(), b.end());
        res = add(a, b);
        cnt++;
    }
    cout<<res<<"\n";
    cout<<cnt<<"\n";

    return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值