PAT Level A 1019 Common Palindrome

Link to original title

A number is a palindrome if it reads exactly the same from front to back as from back to front.

For example, 1234321 is a palindromic number.

All single digits are palindromic numbers.

We generally think of palindromes in decimal, but the concept of palindromes can also be applied to numbers in other bases.

An integer N has a total of k+1 digits in base b, and the i-th digit is ai, (0≤i≤k), then N=∑ki=0(aibi).

In general, 0≤ai<b, and ak≠0.

If ai=ak−i is satisfied for any i, then N is a palindromic number in base b.

0 is represented as 0 in any base, and is regarded as a palindrome number.

Now given an integer N, please judge whether it is a palindrome in b-ary representation.

Input format
One line contains two integers N and b.

Output Format
The output consists of two lines.

If N is a palindrome in base b, the first line outputs Yes, otherwise outputs No.

The second line outputs the representation of N in base b, including k+1 integers. It is required to output ak, ak−1,...,a0 in sequence, and the integers are separated by spaces.

Data range
0≤N≤109,
2≤b≤109
Input sample 1:
27 2
Output sample 1:
Yes
1 1 0 1 1
Input sample 2:
121 5
Output sample 2:
No
4 4 1

My solution:

#include <bits/stdc++.h>
using namespace std;
const int N = 1e9 + 10;
int n, b;
vector<int> nums;
bool check(){
    for(int i = 0, j = nums.size() - 1; i < j; i ++, j --){
        if(nums[i] != nums[j]){
            return false;
        }
    }
    return true;
}
int main(){
    cin >> n >> b;
    if(!n) nums.push_back(0);
    while(n) nums.push_back(n%b), n/=b;
    if(check()) puts("Yes");
    else puts("No");
    cout << nums.back();
    for(int i = nums.size() - 2; i >= 0; i -- ) cout << " " << nums[i];
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45660485/article/details/126066042