1、因为没看清题目要求,WA了好几次。。。囧。。。
2、题目还是比较简单的,暴力法判断是否为回文即可,不过不能被假象迷惑,我很清楚到后面章节就要被狂虐了。。。
/*
ID:mrxy564
PROG:palsquare
LANG:C++
*/
#include <cstdio>
using namespace std;
bool is_pal(int *a,int cnt){
for(int i=0;i<cnt/2;i++)
if(a[i]!=a[cnt-1-i]) return false;
return true;
}
int main()
{
freopen("palsquare.in","r",stdin);
freopen("palsquare.out","w",stdout);
int base,temp,cnt,cnt2;
int a[20],b[10];
while(scanf("%d",&base)==1){
for(int i=1;i<=300;i++){
temp=i*i;cnt=cnt2=0;
while(temp){
a[cnt++]=temp%base;
temp/=base;
}
temp=i;
while(temp){
b[cnt2++]=temp%base;
temp/=base;
}
if(is_pal(a,cnt)){
for(int i=cnt2-1;i>=0;i--){
if(b[i]>=0&&b[i]<10)
printf("%d",b[i]);
else
printf("%c",b[i]-10+'A');
}
printf(" ");
for(int i=0;i<cnt;i++){
if(a[i]>=0&&a[i]<10)
printf("%d",a[i]);
else
printf("%c",a[i]-10+'A');
}
printf("\n");
}
}
}
return 0;
}
官方题解:
We generate all the squares from 1 to 300 and check to see which are palindromes.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <ctype.h> #include <math.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 "" */ void numbconv(char *s, int n, int b) { int len; if(n == 0) { strcpy(s, ""); return; } /* 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'; } void main(void) { char s[20]; char t[20]; int i, base; FILE *fin, *fout; fin = fopen("palsquare.in", "r"); fout = fopen("palsquare.out", "w"); assert(fin != NULL && fout != NULL); fscanf(fin, "%d", &base); for(i=1; i <= 300; i++) { numbconv(s, i*i, base); if(ispal(s)) { numbconv(t, i, base); fprintf(fout, "%s %s\n", t, s); } } exit(0); }