USACO-Section 1.2 Daul Palindromes[...]

2017-05-29
题目大意:

输入两个整数N,S(1<=N<=15,0<S<10 000),求从S+1起的前N个多
(>=2)进制(二进制~十进制)下的回文数。 
回文数是指从左到右和从右到左看起来一样的数,而且它的左右两端不能为数
字0。比如33就是回文数,而0110则不是。
有的数字在10进制下不是回文数,如26。但是263进制下为222,是回文
数。

题解:

题目要求按从小到大的顺序输出前N个满足条件的十进制数,只要循环递增S的值,符合在两个进制下为回文数就将其输出即可。

代码如下:

/*
ID: madara01
PROG: dualpal
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#define cin fin
#define cout fout
#define MAX 10

using namespace std;

bool isPalindrome(string s) //判断s表示的数是否为回文数
{
    int sl = s.length();
    int l = sl/2 +1;
    for(int i = 0; i<l; i++)
    {
        if(s[i] != s[sl-i-1])  return false;
    }
    return true;
}

string astring(int a) { 
//把int转化成string -_-||因为提交编译错误,目前先这么吧...
    char c = a+'0';
    string m;
    m = m + c;
    return m;
}

bool result(int number) //判断number是否为符合题意的解
{
    int base,ac = 0; //base表示进制,ac表示符合的进制数
    int temp;
    string s;
    for(base = 2; base <= 10; base ++)
    {
        s = "";
        temp = number;
        if(temp % base == 0)  continue;  //末端为'0'不可能是回文数
        while(temp)
        {
            s = s + astring(temp%base);
            temp = temp / base;
        }
        if(isPalindrome(s))  ac++;
        if(ac >= 2)  return true;
    }
    return false;
}

int main(int argc, char **argv)
{
    int n,s;
    ofstream fout ("dualpal.out");
    ifstream fin ("dualpal.in");
    cin >> n >> s;
    s ++;  //所求的解为大于s的数
    while(n>0)
    {
        while(!result(s)) s++;
        cout << s << endl;
        n--;  s++;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值