标签:相等 change sed i++ 进制转换 ber with alt ase
A number that will be the same when it is written forwards or backwards is known as a Palindromic Number. For example, 1234321 is a palindromic number. All single digit numbers are palindromic numbers.
Although palindromic numbers are most often considered in the decimal system, the concept of palindromicity can be applied to the natural numbers in any numeral system. Consider a number N>0 in base b≥2, where it is written in standard notation with k+1 digits a?i?? as (. Here, as usual, 0for all i and a?k?? is non-zero. Then N is palindromic if and only if a?i??=a?k?i?? for all i. Zero is written 0 in any base and is also palindromic by definition.
Given any positive decimal integer N and a base b, you are supposed to tell if N is a palindromic number in base b.
Each input file contains one test case. Each case consists of two positive numbers N and b, where 0 is the decimal number and 2 is the base. The numbers are separated by a space.
For each test case, first print in one line Yes
if N is a palindromic number in base b, or No
if not. Then in the next line, print N as the number in base b in the form "a?k?? a?k?1?? ... a?0??". Notice that there must be no extra space at the end of output.
27 2
Yes
1 1 0 1 1
121 5
No
4 4 1
解题思路:
本题有多组测试数据,每组数据给出一个十进制数字n,与目标进制b,要求将b转化为b进制后,判断转化完成的数字是否为回文数字。
我们可以写一个函数,将十进制数字n转化为b进制并将其每一位都记录在一个容器num中,之后从num第一位开始到中心为止,判断该位与其对称位置是否全相等即可。若全相等,则目标数字是回文数字,否则不是回文数字。
AC代码
1 #include <bits/stdc++.h> 2 using namespace std; 3 vector<int> num; //用来储存进制转换后数字的容器 4 void changeRadix(int n, int radix){ //进制转换函数 5 while(n){ 6 int temp; 7 temp = (n % radix); 8 num.push_back(temp); 9 n /= radix; 10 } 11 } 12 bool judge(){ //回文判断函数 13 int len = num.size(); 14 for(int i = 0; i < len / 2; i++){ 15 if(num[i] != num[len - i - 1]) //判断该位置与其对称位置是否相等 16 return false; 17 } 18 return true; 19 } 20 int main() 21 { 22 int n, b; 23 while(scanf("%d%d", &n, &b) != EOF){ //输入数字n与目标进制b 24 if(n == 0){ //0的所有进制都是回文数 25 printf("Yes\n"); 26 printf("0\n"); 27 continue; 28 } 29 num.clear(); //清空容器num 30 changeRadix(n, b); //将n转化为b进制 31 if(judge()){ //判断转换进制后是否为回文数字 32 printf("Yes\n"); //是则输出Yes 33 //由于我们是逆序储存转换后的数字的,所以在输出前要将其反转 34 reverse(num.begin(), num.end()); 35 bool flag = false; 36 for(auto i : num){ //输出转换后数字 37 if(flag) 38 printf(" "); 39 else 40 flag = true; 41 cout << i; 42 } 43 printf("\n"); 44 }else{ //不是回文数字输出No,其余操作同上 45 printf("No\n"); 46 reverse(num.begin(), num.end()); 47 bool flag = false; 48 for(auto i : num){ 49 if(flag) 50 printf(" "); 51 else 52 flag = true; 53 cout << i; 54 } 55 printf("\n"); 56 } 57 } 58 return 0; 59 }
PTA (Advanced Level)1019 General Palindromic Number
标签:相等 change sed i++ 进制转换 ber with alt ase
原文地址:https://www.cnblogs.com/suvvm/p/10205802.html