(Python实现)PAT 1019 General Palindromic Number (20 分)

1019 General Palindromic Number (20 分)
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.
如果一个数字在向前或向后写的时候是相同的,那么这个数字就是回文数字。例如,1234321是一个回文数。所有的单位数都是回文数。

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
虽然回文数最常被认为是十进制,回文性的概念可以应用于任何数字系统中的自然数。假设一个以b为基数≥2的数N>0,用标准符号表示,k+1个数字a i为
在这里插入图片描述

Here, as usual, 0≤a​i​​ ​​ for all i. Zero is written 0 in any base and is also palindromic by definition.
这里,和往常一样,0≤a i 对于所有i, 0在任何底数下都写成0,而且根据定义,它也是回文的。

Given any positive decimal integer N and a base b, you are supposed to tell if N is a palindromic number in base b.
给定任何正的十进制整数N和以b为基数,你应该告诉N是否是以b为基数的回文数。

Input Specification:
Each input file contains one test case. Each case consists of two positive numbers N and b, where 0 每个输入文件包含一个测试用例。每个案例包括两个正数N和b,其中0 < N≤10的9次方是十进制数和2 b≤≤10的9次方是基础。这些数字用空格隔开。

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 "a​k​ ak−1​​ … a0​ ". Notice that there must be no extra space at the end of output.
对于每个测试用例,如果N是以b为基数的回文数,则首先在一行中打印’ Yes ‘,否则打印’ No '。然后在下一行,打印出以b为基数的数字N,格式为“ak ak−1…”a0”。注意,在输出的末尾不能有多余的空格。

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

作者:CHEN, Yue
单位:浙江大学
代码长度限制:16 KB
时间限制:400 ms
内存限制:64 MB

解题思路:
首先将转换后的数的每一个组成部分用数组存储起来,遍历这个数组判断是否为回文数。
注意,转换后的数的每一部分不一定在[0-9],考虑2356 42 这个测试用例,答案应该是No 1 14 4。

代码:

def change(n, radix):
    if n == 0:
        return '0'
    result = []
    while n != 0:
        result.insert(0, str(n%radix))
        n = n // radix
    return result

if __name__ == '__main__':
    line = input().split(' ')
    n = int(line[0])
    radix = int(line[1])
    num = change(n, radix)
    result = ''
    if len(num) == 1:
        result = 'Yes' + '\n' + num[0]
    else:
        for x in range(len(num)//2):
            if num[x] != num[len(num)-1-x]:
                result = 'No' + '\n' + ' '.join(num)
                break
        if result == '':
            result = 'Yes' + '\n' + ' '.join(num)
    print(result)

提交记录:
(Python实现)PAT 1019 General Palindromic Number (20 分)_第1张图片

你可能感兴趣的:(每日一题,python)