【每日一题0915】最小排列

:woman_mage:给定一个数字,请编写一个函数,求出绝对值最小的组合。
备注:组合时0不可排在前面。

示例:
输入:312,输出:123
输入:-20,输出:-20

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

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

assert min_permutation(312) == 123
assert min_permutation(29394) == 23499
assert min_permutation(-20) == -20
assert min_permutation(0) == 0
def min_permutation(n:int):
    s=str(n)
    res=[]
    for i in s:
        res.append(i)
    if n>=0:
        res.sort()
        return int(''.join(res))
    else:
        res.sort(reverse=True)
        return int('-'+''.join(res[:-1]))
import itertools


def min_permutation(n: int) -> int:

    str_n = str(abs(n))
    min_res = abs(n)
    tmp = itertools.permutations(str_n, len(str_n))
    for item in tmp:
        num = int("".join(item))
        if len(str(num)) == len(str_n):
            if n > 0:
                min_res = min(min_res, num)
            else:
                min_res = max(min_res, num)

    if n >= 0:
        return min_res
    return -min_res


def min_permutation_oth(n: int) -> int:
    s = str(n)
    res = []
    tmp = 0
    for i in s:
        if i == "0":
            tmp += 1
        elif i.isdigit():
            res.append(i)
    if n >= 0:
        res.sort()
        res.insert(1, tmp * "0")
        return int(''.join(res))
    else:
        res.sort(reverse=True)
        return int('-' + ''.join(res) + tmp*"0")


if __name__ == "__main__":
    assert min_permutation(312) == 123
    assert min_permutation(29394) == 23499
    assert min_permutation(-29394) == -99432
    assert min_permutation(-20) == -20
    assert min_permutation(0) == 0
    assert min_permutation(2000000) == 2000000
    assert min_permutation(2000020) == 2000002
    assert min_permutation(-2000000) == -2000000

    assert min_permutation_oth(312) == 123
    assert min_permutation_oth(29394) == 23499
    assert min_permutation_oth(-29394) == -99432
    assert min_permutation_oth(-20) == -20
    assert min_permutation_oth(0) == 0
    assert min_permutation_oth(2000000) == 2000000
    assert min_permutation_oth(2000020) == 2000002
    assert min_permutation_oth(-2000000) == -2000000
def min_permutation(n: int) -> int:
    if n == 0:
        return 0
    res = [i for i in str(n)]
    if n > 0:
        res.sort()
        # 将所有0移动第一个数字右边
        len_a = len(res)
        res = [i for i in res if i != '0']
        len_b = len(res)
        for i in range(len_a-len_b):
            res.insert(1, '0')
        return int(''.join(res))
    else:
        res.sort(reverse=True)
        return int('-'+''.join(res[:-1]))

assert min_permutation(312) == 123
assert min_permutation(29394) == 23499
assert min_permutation(-20) == -20
assert min_permutation(0) == 0
assert min_permutation(120) == 102
assert min_permutation(-102) == -210
 public Integer minPermutation(Integer n) {
        if (n > 0) {
            String s = String.valueOf(n);
            List<Character> collect = s.chars().mapToObj(i -> (char) i).collect(Collectors.toList()).stream().sorted().collect(Collectors.toList());
            String collect1 = collect.stream().map(i -> String.valueOf(i)).collect(Collectors.joining("", "", ""));
            return Integer.parseInt(collect1);
        } else if (n < 0) {
            int abs = Math.abs(n);
            String s = String.valueOf(abs);
            List<Character> collect = s.chars().mapToObj(i -> (char) i).collect(Collectors.toList()).stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
            String collect1 = collect.stream().map(i -> String.valueOf(i)).collect(Collectors.joining("", "", ""));
            return -Integer.parseInt(collect1);
        } else {
            return 0;
        }

    }


    @Test
    public void testMinPermutation() {
        assert minPermutation(312).equals(123);
        assert minPermutation(29394).equals(23499);
        assert minPermutation(-20).equals(-20);
        assert minPermutation(0).equals(0);
    }
def min_permutation(n: int) -> int:
    nL = list(str(abs(n)))
    nL.sort()
    count = nL.count('0')
    nL = nL[count:]
    nL = [nL[0]] + ['0']*count +nL[1:] if nL!=[] else ['0']
    if n > 0 :
        return int(''.join(nL))
    else:
        return int('-' + ''.join(nL))


assert min_permutation(312) == 123
assert min_permutation(29394) == 23499
assert min_permutation(-20) == -20
assert min_permutation(0) == 0
def min_permutation(n: int) -> int:
    nums = sorted(str(n))
    if nums[0] == "-":
        result = nums[1:]
        result.reverse()
        return -int("".join(result))
    else:
        if nums[0] == "0":
            for i in range(len(nums)):
                if nums[i] != "0":
                    nums[i], nums[0] = nums[0], nums[i]
                    break
        return int("".join(nums))


assert min_permutation(312) == 123
assert min_permutation(29394) == 23499
assert min_permutation(-20) == -20
assert min_permutation(0) == 0
def min_permutation(n: int) -> int:
    l = list(str(n))
    # 按照从小到大排序
    l.sort()
    data1 = []
    data2 = ""
    # 如果数字位数为1,返回数字n本身
    if len(str(n)) == 1:
        return n
    # 如果数字位数大于1
    else:
        # 将除-和0外的数字放入data1列表
        for i in l:
            if i != '-' and i != '0':
                data1.append(i)
        # 如果有-,data2第一位为负数
        if '-' in l:
            data2 += '-'
        # 如果有0,data2先放入data1的最小数,然后放入0
        if '0' in l:
            data2 += data1[0] + '0' * (str(n).count('0'))
        # 如果没有0,data2放入data1的最小数
        else:
            data2 += data1[0]
        # 返回data2+data1的第二位开始的数字
        return int(data2 + ''.join(data1[1:]))


assert min_permutation(312) == 123
assert min_permutation(29394) == 23499
assert min_permutation(-20) == -20
assert min_permutation(0) == 0
关闭