PAT_甲级_1136 A Delayed Palindrome (20point(s)) (C++)【签到题/字符串处理】

目录

1,题目描述

 题目大意

2,思路

3,AC代码

4,解题过程


1,题目描述

  • palindrome:回文数;

Sample Input 1:

97152

 

Sample Output 1:

97152 + 25179 = 122331
122331 + 133221 = 255552
255552 is a palindromic number.

 

Sample Input 2:

196

 

Sample Output 2:

196 + 691 = 887
887 + 788 = 1675
1675 + 5761 = 7436
7436 + 6347 = 13783
13783 + 38731 = 52514
52514 + 41525 = 94039
94039 + 93049 = 187088
187088 + 880781 = 1067869
1067869 + 9687601 = 10755470
10755470 + 07455701 = 18211171
Not found in 10 iterations.

 题目大意

判断一个数在10次操作(将这个数字与逆序的数字相加,并将结果作为新的数字)之内能否变为回文数。

 

2,思路

1,bool isPalindrome(string s):判断数字(字符串形式)是否为回文数;

2,string add(string a):迭代操作,a与a的逆序相加;

 

3,AC代码

#include<bits/stdc++.h>
using namespace std;
bool isPalindrome(string s){
    int i = 0, j = s.size()-1;
    while(i < j && s[i] == s[j]){
        i++;j--;
    }
    if(i < j) return false;
    else return true;
}
string add(string a){
    string b = a, c = "";       //c = a + b
    reverse(b.begin(), b.end());
    int carry = 0;
    for(int i = a.size()-1; i >= 0; i--){
        int tem = (a[i]-'0') + (b[i]-'0') + carry;
        if(tem >= 10){          // !!!>=
            tem -= 10;
            carry = 1;
        }else carry = 0;
        c += ('0' + tem);
    }
    if(carry == 1) c += '1';
    reverse(c.begin(), c.end());
    cout<<a<<" + "<<b<<" = "<<c<<endl;
    return c;
}
int main(){
#ifdef ONLINE_JUDGE
#else
    freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
    string s;
    cin>>s;
    int step = 10;
    while(step--){
        if(isPalindrome(s)){
            cout<<s;
            printf(" is a palindromic number.");
            return 0;
        }
        s = add(s);
    }
    printf("Not found in 10 iterations.");
    return 0;
}

4,解题过程

一发入魂o(* ̄▽ ̄*)ブ

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值