/* ID:tianlin2 PROG:dualpal LANG:C++ */ #include <iostream> #include <string> #include <fstream> using namespace std; bool ps(int n,int ary) { char a[]={'0','1','2','3','4','5','6','7','8','9'}; string b; while(n!=0) { b=b+a[n%ary]; n=n/ary; } for(int x=0,y=b.size()-1;x<b.size()/2&&y>=b.size()/2;++x,--y) { if(b[x]!=b[y]) return false; } return true; } int main() { ofstream fout("dualpal.out"); ifstream fin("dualpal.in"); int a,b,c=0; fin>>a>>b; int i=b+1; int j=0; while(j!=a) { int x=0; for(int y=2;y!=11;++y) { if(ps(i,y)) ++x; if(x>1) break; } if(x==2) { fout<<i<<endl; ++j; } ++i; } //system("pause"); return 0; } 做法基本上和官方的相同,不过还是官方的简便,悲剧! 官方答案: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> /* is string s a palindrome? */ int ispal(char *s) { char *t; t = s+strlen(s)-1; for(t=s+strlen(s)-1; s<t; s++, t--) if(*s != *t) return 0; return 1; } /* put the base b representation of n into s: 0 is represented by "" */ char* numbconv(char *s, int n, int b) { int len; if(n == 0) { strcpy(s, ""); return s; } /* figure out first n-1 digits */ numbconv(s, n/b, b); /* add last digit */ len = strlen(s); s[len] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[n%b]; s[len+1] = '/0'; return s; } /* is number n a dual palindrome? */ int isdualpal(int n) { int i, j, npal; char s[40]; npal = 0; for(i=2; i<=10; i++) if(ispal(numbconv(s, n, i))) npal++; return npal >= 2; } void main(void) { FILE *fin, *fout; int n, s; fin = fopen("dualpal.in", "r"); fout = fopen("dualpal.out", "w"); assert(fin != NULL && fout != NULL); fscanf(fin, "%d %d", &n, &s); for(s++; n>0; s++) { if(isdualpal(s)) { fprintf(fout, "%d/n", s); n--; } } exit(0); }