shu_1180 回文数(一)

版权声明:本文为博主原创文章,未经博主同意不得转载。 https://blog.csdn.net/naturelan44/article/details/37563425

http://202.121.199.212/JudgeOnline/problem.php?cid=1079&pid=21


分析: 回文串推断,字符串处理

             1. atoi 函数(ascii tointeger 将字符串转换成整型数)

                 头文件: #include <stdlib.h>

                int atoi(const char *nptr);

                 因为程序中使用string类,所以应该用 str.c_str() 将string转为c语言下的字符串数组。

             2. itoa函数(与atoi功能相反)

                 char*itoa(intvalue,char*string,intradix); (与atoi使用方法差别)

            3. stringstream

                头文件: #include <sstream>

               

input:

3
1 2 3
20 17 23 54 77 60
111 222 333 444 555 666 777 888 999


#include <iostream>
#include <stdio.h>
#include <string>
#include <sstream>
using namespace std;
#define MAXN 60

int main()
{
    freopen("in.txt","r",stdin);

    string s;
    stringstream ss;
    int t;
    int n,a[MAXN];
    cin>>t;
    getchar();  //读取换行
    while(t--){
        getline(cin,s);
        ss.clear();
        ss.str(s); //ss<<s;
        n=0;
        while(1){
            ss>>a[n++];
            if(ss.fail()) break;
        }
        for(int i=0;i<n-1;i++) cout<<a[i]<<" "; //n比数字多1个
        cout<<endl;
    }
    return 0;
}
        

output:     


   输出到double一样;         

  有关string的使用方法在string类说明中再行分析。

             

代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <string>
#include <sstream>
#include <stdlib.h>
#include <algorithm>
using namespace std;
#define MAXN 10000
 
int cnt;
string s[MAXN];
 
bool palindrome(string e)
{
    for(int i=0,j=e.length()-1;i<e.length();i++,j--){
        if(e[i]!=e[j]) return false;
    }
    return true;
}
 
void deal(string e)
{
    int a;
    string x=e;
    while(1){
        cnt++;
        if(cnt>8) {cnt=0;break;}
        a=atoi(x.c_str());
        reverse(x.begin(),x.end());
        a +=atoi(x.c_str());  //123+321
        stringstream ss;
        ss<<a; ss>>x;
        if(palindrome(x)) {
            break;
        }
    }
    printf("%d
",cnt);
}
 
int main()
{
    int n;
    string str;
    scanf("%d",&n);
    while(n--){
        cin>>str;
        cnt=0;
        deal(str);
    }
    return 0;
}


原文地址:https://www.cnblogs.com/mqxnongmin/p/10872141.html