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\n",cnt);
}
int main()
{
int n;
string str;
scanf("%d",&n);
while(n--){
cin>>str;
cnt=0;
deal(str);
}
return 0;
}