[算法]数字重组整除问题

数字重组整除问题

题目地址

题目描述

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的数,如果有,输出最大的那个

思路解析
  1. 将数字全排列
  2. 判断数字是否是17的整数倍
  3. 选择最大的一个数字输出,没有就输出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)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值