USACO 1.2.4 Palindromic Squares 回文平方数

Palindromic Squares
Rob Kolstad

Palindromes are numbers that read the same forwards as backwards.The number 12321 is a typical palindrome.

Given a number base B (2 <= B <= 20 base 10), print all theintegers N (1 <= N <= 300 base 10) such that the square of N ispalindromic when expressed in base B; also print the value of thatpalindromic square. Use the letters 'A', 'B', and so on to representthe digits 10, 11, and so on.

Print both the number and its square in base B.

PROGRAM NAME: palsquare

INPUT FORMAT

A single line with B, the base (specified in base 10).

SAMPLE INPUT (file palsquare.in)

10

OUTPUT FORMAT

Lines with two integers represented in base B. Thefirst integer is the number whose square is palindromic;the second integer is the square itself.

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

解题思路:
        该题是说输入一个十进制整数B,判断300以下数据的平方的B进制为回文数,并输出。那么,我们要做的工作分为两步:一、将该数据平方转换成B进制;
二、判断该B进制表示数是否为回文数。这样的要求我们放在两个函数完成即可。进制转换采用除数取余法,这里我借助栈来完成,回文数判断直接扫描数组,前后依
次比较。
代码如下:
/*
ID:ayludon3
LANG: C++
TASK: palsquare
*/
#include <iostream>
#include <fstream>
#include <stack>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;

char jinzhi[100],len;
int transf(int a,int b)      //任意十进制数a转换成b进制
{
    int c,d,i=0;
    stack<char>s;
    while(a)
    {
        c=a/b;
        d=a%b;
        if(d>=10)
            s.push('A'+d-10);
        else
            s.push('0'+d);
        a=c;
    }
    while(!s.empty())
    {
        jinzhi[i]=s.top();
        i++;
        s.pop();
    }
    len=i;
//    for(int j=0;j<i;j++)
//        cout<<jinzhi[j]<<' ';
    return 0;
}


bool judge(char a[])
{
    int i;
    for(i=0;i<len/2+1;i++)
        if(a[i]!=a[len-i-1])
            return false;
    return true;
}

int main()
{
//    ifstream fin ("palsquare.in");
//    ofstream fout ("palsquare.out");
    int i,j,n,len1;
    char temp[100];
//    fin>>n;
    cin>>n;
    for(i=1;i<=300;i++)
    {
        transf(i*i,n);
        if(judge(jinzhi))
        {
            for(j=0;j<len;j++)
                temp[j]=jinzhi[j];
            len1=len;
            transf(i,n);
            for(j=0;j<len;j++)
//                fout<<jinzhi[j];
            cout<<jinzhi[j];
//            fout<<' ';
            cout<<' ';
            for(j=0;j<len1;j++)
//                fout<<temp[j];
            cout<<temp[j];
//            fout<<endl;
            cout<<endl;
        }
    }
    return 0;
}

 

你可能感兴趣的:(USACO 1.2.4 Palindromic Squares 回文平方数)