usaco 1.2 Palindromic Squares题解

3 篇文章 0 订阅
2 篇文章 0 订阅

题目

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 the integers N (1 <= N <= 300 base 10) such that the square of N is palindromic when expressed in base B; also print the value of that palindromic square. Use the letters ‘A’, ‘B’, and so on to represent the 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. The first integer is the number whose square is palindromic; the second integer is the square itself. NOTE WELL THAT BOTH INTEGERS ARE IN BASE B!
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

题目翻译&&解析

题目翻译:

    题目的意思是说,输入一个数字N表示进制,进制的区间为2~20,然后在确定进制以后找出(1~300)的平方里的所有符合该进制的回文数。
    回文数即为正着读反着读,结果一样的数字,形如,12321,123321,等等。123432则不是回文数。

解析:

    本题的重点就是回文的判定,和进制的转换。
    1,根据回文数的特点,回文数是轴对称的数字,只需要不断的比较对称位即可,也就是说,在数组中不断的判断arr[i]与arr[n-i]是否相等即可,如果有一位不相等则证明不是回文数。
    2,进制转换。进制转换是一个比较简单的问题,拿10进制转换成任意进制N来说,只要将10进制的数字,不断的与N取模,将模值按照产生的先后顺序,最后产生的排在首位,依次,一个产生的排在最后,即是将10进制的数字转换为N进制的数字的情况。

code

C++
#include <iostream>

using namespace std;

int main()
{
    int n,num;
    cin>>n;
    int arr[310];
    const char a[]="0123456789ABCDEFGHIJ";

    for(int i=1; i<301; i++)//预处理提前得到平方值
    {
        arr[i]=i*i;
    }
    for(int i=1; i<301; i++)
    {
        int flag=0;
        string mystring="";
        num=arr[i];
        while(num!=0)
        {
            mystring+=a[num%n];//mystring存放的是回文数字的结果
            num=num/n;
        }
        //cout<<mystring<<endl;
        int len=mystring.length();
        for(int j=0;j<len/2;j++)
        {
            if(mystring[j]!=mystring[len-1-j])//判断是否为回文数
            {
                flag+=1;
                break;
            }
        }
        if(flag==0)
        cout<<i<<" "<<mystring<<endl;



    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值