palsquare解题报告

来源:互联网 发布:coc暗黑训练营升级数据 编辑:程序博客网 时间:2024/05/22 13:32

题目摘要:Palindromes are numbers that readthe same forwards as backwards. The number 12321 is a typical palindrome.

Given a number base B (2 <= B <= 20base 10), print all the integers N (1 <= N <= 300 base 10) such that thesquare of N is palindromic when expressed in base B; also print the value ofthat palindromic square. Use the letters 'A', 'B', and so on to represent thedigits 10, 11, and so on.

Print both the number and its square inbase B.

题目大意:给定一个B(2<=B<=20)进制,编写一个程序输出从1到300且它的平方用B进制表示时是回文的数,用’A’,’B’,.......等表示10,11;

输入输出样例

SAMPLE INPUT (file palsquare.in)

10

SAMPLE OUTPUT (file palsquare.out)

1 1

2 4

3 9

11 121

22 484

26 676

101 10201

111 12321

121 14641

202 40804

212 44944

264 69696

解题思路:将1到300所有数及其平方转换成B进制的数然后判断平方后的数是否为回文,是的话就输出,否则不输出。

代码

#include<iostream>

#include<cstring>

using namespace std;

 

void change(int k, int B, char str3[])

{

       intt=k;

       inta=0;

       intj=0;

       intn=0;

       while((n=t/B)!=t)

       {

              a=t%B;

              t=n;

              if(a>=10)

                     str3[j++]='A'+(a-10);

              else

                     str3[j++]='0'+a;

       }

       char*p1;

       char*p2;

       chartemp;

       p1=str3;

       p2=str3+j-1;

       while(p1<p2)

       {

              temp=*p1;

              *p1=*p2;

              *p2=temp;

              p1++;

              p2--;

       }

       str3[j]='\0';

}

int check(char str4[])

{

       intlen=strlen(str4);

       char*pstart;

       char*pend;

       pstart=str4;

       pend=str4+len-1;

       while((*pstart==*pend)&&(pstart<pend))

       {

              pstart++;

              pend--;

       }

       if(pstart<pend)

              return0;

       else

              return1;

}

int main(void)

{

       intB;

       inti;

       cin>>B;

       for(i=1;i<=300; i++)

       {

              charstr1[50];

              charstr2[50];

              inth=i*i;

              change(h,B ,str1);

              if(check(str1))

              {

                     change(i,B, str2);

                     cout<<str2<<'';

                     cout<<str1<<endl;

              }

       }

       return0;

}

解题感想:将一个数转换为B进制的数是李才林从一本算法书上看到的,比我们在校赛上用的方法优化好多,所以现在直接拿过来用,转换为B进制数后在用check函数判断是否回文即可,以后有时间要多多看书啊。

原创粉丝点击