(PAT甲级)1019 General Palindromic Number 进制转换+回文数 (进制转换问题的实用技巧)

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 ai​ as ∑i=0k​(ai​bi). Here, as usual, 0≤ai​

Given any positive decimal integer N and a base b, you are supposed to tell if N is a palindromic number in base b.

Input Specification:

Each input file contains one test case. Each case consists of two positive numbers N and b, where 0

Output Specification:

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 "ak​ ak−1​ ... a0​". Notice that there must be no extra space at the end of output.

Sample Input 1:

27 2

Sample Output 1:

Yes
1 1 0 1 1

Sample Input 2:

121 5

Sample Output 2:

No
4 4 1

 题目的大意是,判断某一个数字在某个进制下是不是回文数,并且由高位到低位输出该数字

个人建议,对于这种进制转换的问题,保险的做法是直接按位模拟,而不是直接用字符串模拟

因为进制可能取得非常大,如果是36进制以内,尚且可以使用字母表示,但如果是几百几千,甚至几亿进制,用字符串模拟就非常力不从心,而且一不留神就容易错,况且字符串模拟本身效率也不是很高。

因为我是按位模拟,因此没有踩到一些题目可能隐藏的坑。下面说说我猜测的坑点。题目有个说明是,进制可能非常大,达到1e9,因此我们会发现,任何一个数,如果小于本身的进制的话,那就只有一位,也就永远是回文数。很多人的判断可能还停留在比对字符串是否首尾吻合,这其实是很容易出错的。

以下是AC代码,里面关于进制转换的部分可供大家参考。

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
typedef long long ll;
struct number {
	vector nums;//从低位到高位排列
	ll base;
	number(ll num,ll base) {
		this->base = base;
		nums.push_back(num);
		while (nums.back() >= base) {
			ll next = nums.back() / base;
			nums.back() %= base;
			nums.push_back(next);
		}
	}
	bool isPalindromic() {
		for (int i = 0; i < nums.size() / 2; ++i) {
			if (nums[i] != nums[nums.size() - 1 - i])return false;
		}
		return true;
	}
	string output() {
		stringstream ss;
		for (int i = nums.size()-1; i >= 0; i--) {
			ss << nums[i];
			if (i)ss << " ";
		}
		return ss.str();
	}
};
int main() {
	ll num, base;
	cin >> num >> base;
	number n(num,base);
	cout << (n.isPalindromic() ? "Yes" : "No") << endl;
	cout << n.output();
	return 0;
}

你可能感兴趣的:(算法,c++,c语言,pat考试)