https://www.dotcpp.com/oj/problem1618.html
问题 1618: [蓝桥杯][算法训练VIP]回文数
时间限制: 1Sec 内存限制: 128MB 提交: 104 解决: 28
题目描述
若一个数(首位不为零)从左向右读与从右向左读都一样,我们就将其称之为回文数。
例如:给定一个10进制数56,将56加65(即把56从右向左读),得到121是一个回文数。
又如:对于10进制数87:
STEP1:87+78 = 165 STEP2:165+561 = 726
STEP3:726+627 = 1353 STEP4:1353+3531 = 4884
在这里的一步是指进行了一次N进制的加法,上例最少用了4步得到回文数4884。
写一个程序,给定一个N(2< =N< =10或N=16)进制数M(其中16进制数字为0-9与A-F),求最少经过几步可以得到回文数。
如果在30步以内(包含30步)不可能得到回文数,则输出“Impossible!”输入
两行,N与M
输出
如果能在30步以内得到回文数,输出“STEP=xx”(不含引号),其中xx是步数;否则输出一行”Impossible!”(不含引号)
样例输入
9 87
样例输出
STEP=6
#include<bits/stdc++.h>
using namespace std;
int a[1001],radix,sum;
string s;
bool isPal(int n){
for(int i=1;i<=n/2;++i){
if(a[i]!= a[n-i+1])
return false;
}
return true;
}
int add(int n)
{
int c[1001] = { 0 };//定义临时数组,表示两数的和
for (int i = 1; i <= n; i++)//进制数相加
{
c[i] = a[i] + a[n - i + 1] + c[i];
c[i + 1] = c[i] / radix;
c[i] %= radix;
}
if (c[n + 1])//保留进位
n++;
for (int i = n; i >= 1; i--)
{
a[i] = c[i];
}
return n;
}
int main()
{
cin >> radix >> s;//radix代表进制 s代表字符串
int n = s.length();
for(int i=1;i<=n;++i)
{
if(s[i-1] < 65) a[i]=s[i-1]-'0';
else a[i]=s[i-1]-'55';//注意16进制数 -‘55’将A-F转化为10-15
}
while (sum <= 30)
{
if (isPal(n))
{
cout << "STEP=" << sum;
return 0;
}
sum++;
//printf("$$%d\n",n);
n = add(n);
}
cout << "Impossible!" << endl;
return 0;
}
此程序转载于https://blog.csdn.net/bodhiye/article/details/70739961
Euler Problem-36 十进制二进制回文
https://projecteuler.net/problem=36
Double-base palindromes
Problem 36
The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.
Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.
(Please note that the palindromic number, in either base, may not include leading zeros.)
#include<iostream>
using namespace std;
#define MAX_N 1000000
int reverNum(int n, int base) {
if (base <= 1) return 0;
int x = 0;
while (n) {
x = x * base + n % base;
n /= base;
}
return x;
}
int main() {
int sum = 0, base2, base10;
for (int i = 0 ; i < MAX_N ; ++i) {
base2 = reverNum(i, 2);
base10 = reverNum(i, 10);
if (base2 == base10 && base10 == i) {
sum += i;
}
}
printf("%d\n", sum);
return 0;
}