数字重组整除问题
题目描述
Description
Babul’s favourite number is 17. He likes the numbers which are divisible by 17. This time what he does is that he takes a number N and tries to find the largest number which is divisible by 17, by rearranging the digits. As the number increases he gets puzzled with his own task. So you as a programmer have to help him to accomplish his task.Note: If the number is not divisible by rearranging the digits, then print “Not Possible”. N may have leading zeros.
Input
The first line of input contains an integer T denoting the no of test cases. Each of the next T lines contains the number N.
Output
For each test case in a new line print the desired output.
Sample Input 1
4
17
43
15
16
Sample Output 1
17
34
51
Not Possible
题目解析
给定的一个数字,问该数字的全排列是否有可以整除17的数,如果有,输出最大的那个
思路解析
- 将数字全排列
- 判断数字是否是17的整数倍
- 选择最大的一个数字输出,没有就输出Not Possible
注意
题目中有说可以给定0
虽然0%17==0,但0不能被任何数整除,因此一定要把0排除在外
代码实现(python)
全排列的复杂度很高,暂时想不到更好的方法解决
可以使用map,缓存结果,但缓存的话会占用大量空间,并且速度未必会提升
from itertools import permutations
if __name__ == '__main__':
for _ in range(int(input())):
s = input()
array = list(map(lambda x: x, s)) # 把输入字符转成一个字符数组
pailie = list(set(permutations(array))) # 将数字全排列并去重
max_z = 0
for x in pailie:
z = int("".join(x)) # 字符数组拼接成一个字符串,并转为数字
if z % 17 == 0:
max_z = max(max_z, z) # 由于一个全排列可能有多个满足条件的数,因此选择一个最大的
if max_z == 0: # 注意,这里0一定要排除掉
print("Not Possible")
else:
print(max_z)