【USACO】双重回文数

题目描述

如果一个数从左往右读和从右往左读都是一样,那么这个数就叫做“回文数”。例如,12321就是一个回文数,而77778就不是。当然,回文数的首和尾都应是非零的,因此0220就不是回文数。 事实上,有一些数(如21),在十进制时不是回文数,但在其它进制(如二进制时为10101)时就是回文数。 编一个程序,从文件读入两个十进制数N (1 <= N <= 15)S (0 < S < 10000)然后找出前N个满足大于S且在两种或两种以上进制(二进制至十进制)上是回文数的十进制数,输出到文件上。 本问题的解决方案不需要使用大于4字节的整型变量。

输入

只有一行,用空格隔开的两个数N和S。

输出

N行, 每行一个满足上述要求的数,并按从小到大的顺序输出。

样例输入

3 25

样例输出

26 27 28

提示

 

来源

 

[提交][状态][讨论版]

 

 

 

#include <stdio.h>
#include <string.h>

/* is string s a palindrome? */
int ispal(char *s){
    char *t;
    t=s+strlen(s)-1;
    for(t=s+strlen(s)-1; s<t; s++, t--)
        if(*s != *t) return 0;
    return 1;
}

/* put the base b representation of n into s: 0 is represented by "" */
char* numbconv(char *s, int n, int b){
    int len;
    if(n==0){
        strcpy(s, "");
        return s;
    }

    /* figure out first n-1 digits */
    numbconv(s, n/b, b);

    /* add last digit */
    len = strlen(s);
    s[len] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[n%b];
    s[len+1] = '\0';
    return s;
}

/* is number n a dual palindrome? */
int isdualpal(int n){
    int i, j, npal;
    char s[40];
    npal = 0;
    for(i=2; i<=10; i++)
         if(ispal(numbconv(s, n, i))) npal++;
    return npal >= 2;
}

int main(){
    int n, s;
    scanf("%d%d", &n, &s);

    for(s++; n>0; s++)
        if(isdualpal(s)){
            printf("%d\n", s);
            n--;
        }

    return 0;
}

 

 

posted @ 2013-04-14 18:29  qilinart  阅读(304)  评论(0编辑  收藏  举报