palsquare解题报告

题目摘要: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函数判断是否回文即可,以后有时间要多多看书啊。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值