1024 Palindromic Number (25分)

题不难。我以为我的已经够简洁了,没想到还有更简洁的,algorithm里面有reverse()函数,可以直接给出逆序结果,方便多了(虽然不用这个也不会很麻烦,但还是学学STL的使用)。一看这题应该要想到用字符模拟运算,看看数据范围就知道了,int类型的数据范围简单的记为10的9次方,有10位数,long long范围简单的记为10的18次方,有19位数,记住这两个范围可以节省一些时间。本题即使用long long也会超出范围。
1 #include <iostream> 2 #include<cstdio> 3 #include<string> 4 using namespace std; 5 bool isPal(string &s){ 6 int lo=0,hi=s.size()-1; 7 while(lo<=hi){ 8 if(s[lo++]!=s[hi--]) 9 return false; 10 } 11 return true; 12 } 13 string add(string &a){ 14 string s; 15 int sa=a.size(); 16 int carry=0,temp=0; 17 for(int i=sa-1,j=0;i>=0||j<sa;i--,j++){ 18 temp=(a[i]-'0')+(a[j]-'0')+carry; 19 carry=temp/10; 20 s+=(temp%10+'0'); 21 } 22 if(carry!=0) 23 s+=(carry+'0'); 24 return s; 25 } 26 int main() 27 { 28 string n; 29 int k,cnt=0; 30 cin>>n>>k; 31 string temp=n; 32 while(cnt<k&&!isPal(temp)){ 33 temp=add(temp); 34 cnt++; 35 } 36 for(int i=temp.size()-1;i>=0;i--) 37 printf("%c",temp[i]); 38 printf("\n%d",cnt); 39 return 0; 40 }
reverse的使用:

浙公网安备 33010602011771号