美文网首页
数字重组整除问题

数字重组整除问题

作者: loick | 来源:发表于2019-11-26 19:31 被阅读0次

数字重组整除问题

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.

思路

就暴力解决(没有想到其他解法,如果有请在下方评论我),尝试所有的排列,找出其中最大的可以整除17的数。需要注意的是‘0’不能算作整除17。

python
import itertools
def solve(s):
    ans = -1
    if s == '0':
        return ans
    for ss in itertools.permutations(s):
        num = int(''.join(ss))
        if num % 17 == 0 and num > ans:
            ans = num
    return ans

C++也有求所有排列的库,Java应该没有,就要自己写一个回溯的算法去遍历所有的排列组合

Java
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = Integer.parseInt(sc.nextLine());
        for (int i = 0; i < n; i++){
            String s = sc.nextLine();
            Arrays.asList(s.toCharArray());
            List<Character> remain = new ArrayList<>();
            for (Character ch: s.toCharArray()){
                remain.add(ch);
            }
            long res = solve("", remain);
            if (res == -1 || s.equals("0")) {
                System.out.println("Not Possible");
            }else{
                System.out.println(res);
            }
        }
    }

    public static long solve(String path, List<Character> remain){
        if (remain.size() == 0){
            return Long.parseLong(path) % 17 == 0 ? Long.parseLong(path):-1;
        }
        long ans = -1;
        for (Character ch: new ArrayList<>(remain)){
            remain.remove(ch);
            ans = Math.max(ans, solve(path+ch, remain));
            remain.add(ch);
        }
        return ans;
    }

}

相关文章

  • 数字重组整除问题

    数字重组整除问题 Description Babul’s favourite number is 17. He l...

  • 数字求和法

    数字求和法即通过一个数各数位上的数字和来判断这个数能否被某个数整除。 1、被3整除数字和是3的倍数 2、被9整除数...

  • 整除问题

    题目链接:https://nanti.jisuanke.com/t/2判断一个数是否能被另一个整数整除是一个挺简单...

  • 任务412-Fizz_Buzz(用test-unit书写单元测试

    同时整除3和5得到"FizzBuzz" 只被3整除得到"Fizz" 只被5整除得到"Buzz" 其余数字输出其字符...

  • 1012数字分类

    问题描述:给定一系列正整数,请按要求对数字进行分类,并输出以下 5 个数字:A1= 能被 5 整除的数字中所有偶数...

  • 03数量技巧——比例倍数

    整除判定: ①口诀: 如果一个数字能够被3或者9整除(数字繁琐弃3弃9),则该数字各个位数上的数字之和能够被3或9...

  • 【Python】-001-变量类型-数字

    1. 自动类型转换 1.1 数字的类型:int和float // 作为运算符表示整除 1.2 float的问题 两...

  • 1311: 数字整除(大数)

    Time Limit: 1 SecMemory Limit: 128 MB Submit: 500Solved: ...

  • 逻辑分支和嵌套三目运算

    问题:找出1~100中所有能被3整除,或者能被5整除,或者既能被3整除又能被5整除的数。   如果只是单纯的问题求...

  • day5-作业

    基础 读程序,总结程序的功能: 执行数字2的20次方 统计数字(1~100)中,能被3整除或者被7整除,但不能同时...

网友评论

      本文标题:数字重组整除问题

      本文链接:https://www.haomeiwen.com/subject/dimywctx.html