【每日一题0930】最近一个大数

:woman_mage:给定一个正整数,请编写一个函数,将它的所有数字重新组合,找出刚好比它大一点儿的那个数字。

实例:
输入:12,返回:21
输入:513,返回:531
输入:144,返回:414

题目难度:中等
题目来源:codewars

def next_bigger(n: int) -> int:
    pass

assert next_bigger(12) == 21
assert next_bigger(513) == 531
assert next_bigger(2017) == 2071
assert next_bigger(414) == 441
assert next_bigger(144) == 414
def next_bigger(n: int) -> int:
    n_list = list(str(n))
    from itertools import permutations
    n_lists = []
    for i in permutations(n_list,len(n_list)):
        n_lists.append(int(''.join(list(i))))
    result = list(set(n_lists))
    result.sort()
    return result[result.index(n)+1]
public Integer nextBig(Integer integer){
        String[] split = integer.toString().split("");
        // 判断低位数是否大于高位数,是则交换并结束循环
        for (int i = split.length-1; i >= 1; i--) {
            if (Integer.parseInt(split[i])>Integer.parseInt(split[i-1])){
                String temp = split[i];
                split[i] = split[i-1];
                split[i-1] = temp;
                break;
            }
        }
        // 重新生成大数
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < split.length; i++) {
            stringBuilder.append(split[i]);
        }
        return Integer.valueOf(stringBuilder.toString());
    }
    @Test
    public void test1(){
        assert nextBig(12).equals(21);
        assert nextBig(513).equals(531);
        assert nextBig(2017).equals(2071);
        assert nextBig(414).equals(441);
        assert nextBig(144).equals(414);
        assert nextBig(11).equals(11);
    }
def next_bigger(n: int) -> int:
    num_list = [int(i) for i in str(n)]
    recombination_list = []

    def perm(n, begin, end):

        if begin >= end:
            num_str = ''
            for one_num in n:
                num_str += str(one_num)
            num = int(num_str)
            recombination_list.append(num)
        else:
            i = begin
            for num in range(begin, end):
                n[num], n[i] = n[i], n[num]
                perm(n, begin + 1, end)
                n[num], n[i] = n[i], n[num]

    perm(num_list, 0, len(num_list))
    recombination_list.sort()
    next_bigger_num = 0
    for i in recombination_list:
        if i > n:
            next_bigger_num = i
            break
    return next_bigger_num


assert next_bigger(12) == 21
assert next_bigger(513) == 531
assert next_bigger(2017) == 2071
assert next_bigger(414) == 441
assert next_bigger(144) == 414
关闭