Mario Cruz (Colombia) & Hugo Rickeboer (Argentina)
A number that reads the same from right to left as when read from left to right is called a palindrome. The number 12321 is a palindrome; the number 77778 is not. Of course, palindromes have neither leading nor trailing zeroes, so 0220 is not a palindrome.
The number 21 (base 10) is not palindrome in base 10, but the number 21 (base 10) is, in fact, a palindrome in base 2 (10101).
Write a program that reads two numbers (expressed in base 10):
- N (1 <= N <= 15)
- S (0 < S < 10000)
and then finds and prints (in base 10) the first N numbers strictly greater than S that are palindromic when written in two or more number bases (2 <= base <= 10).
Solutions to this problem do not require manipulating integers larger than the standard 32 bits.
PROGRAM NAME: dualpal
INPUT FORMAT
A single line with space separated integers N and S.
SAMPLE INPUT (file dualpal.in)
3 25
OUTPUT FORMAT
N lines, each with a base 10 number that is palindromic when expressed in at least two of the bases 2..10. The numbers should be listed in order from smallest to largest.
SAMPLE OUTPUT (file dualpal.out)
26 27 28
思路: 把大于S的数逐个的change,就是转换成2-10进制,计算出是回文数的个数,最后输出N个 还是模拟,枚举的思想。
1 /* 2 ID: shuyang1 3 PROG: dualpal 4 LANG: C++ 5 */ 6 #include <iostream> 7 #include <stdio.h> 8 #include <string.h> 9 using namespace std; 10 11 int buf[100]; 12 int change(int m,int r) //把10进制数转换成r进制数 ,并返回r进制数长度,方便判断回文数。 13 { 14 int s[100]; 15 int i,j,q,p; 16 i=0; 17 while(m!=0) 18 { 19 p=m%r; 20 m=m/r; 21 s[i]=p; 22 i++; 23 } 24 for(j=0;j<i;j++) 25 buf[j]=s[i-j-1]; 26 return i-1; 27 } 28 29 bool ispal(int a[],int length) //判断是否是回文数 30 { 31 int i,j; 32 for(i=0,j=length;i<=j;i++,j--) 33 { 34 if(a[i]!=a[j]) return false; 35 } 36 return true; 37 } 38 39 int main() 40 { 41 freopen("dualpal.in","r",stdin); 42 freopen("dualpal.out","w",stdout); 43 int N,S; 44 int i,j,k; 45 int len; 46 cin>>N>>S; 47 int num[100000]={0}; 48 int ji=0; 49 for(i=S+1;;i++) //逐个计算大于S的数 50 { 51 for(j=2;j<=10;j++) //2-10进制的转换 52 { 53 len=change(i,j); 54 if(ispal(buf,len)) num[i]++; 55 } 56 if(num[i]>=2) 57 { 58 cout<<i<<endl; 59 ji++; 60 } 61 if(ji==N) break; 62 } 63 return 0; 64 }