1136 A Delayed Palindrome

A little bit.

Ideas: large integer addition, palindrome number judgment. It is also necessary to determine whether the number of first input is palindrome, so we use do… While instead of while.

Code:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

bool judge(const string &str)
{
    int i=0,j=str.size()-1;
    while(i<=j){
        if(str[i]!=str[j]) return false;
        i++;
        j--;
    }
    return true;
}

string add(const string& s1,const string& s2)
{
    string sum;
    int carry=0,temp,d;
    for(int i=s1.size()-1;i>=0;i--){
        temp=carry+(s1[i]-'0')+(s2[i]-'0');
        d=temp%10;
        carry=temp/10;
        sum=string(1,d+'0')+sum;
    }
    if(carry>0) sum=string(1,carry+'0')+sum;
    return sum;
}

int main()
{
    string s1,s2;
    cin>>s1;
    int cnt=10;
    do{
        if(judge(s1)){
            cout<<s1<<" is a palindromic number.\n";
            break;
        }
        s2=s1;
        reverse(s2.begin(),s2.end());
        string sum=add(s1,s2);
        cout<<s1<<" + "<<s2<<" = "<<sum<<"\n";
        s1=sum;
    }while(--cnt);
    if(cnt==0) cout<<"Not found in 10 iterations.\n";
    return 0;
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *