정렬 추가문제

less than 1 minute read

Question 1: Smallest Value of the Rearranged Number

You are given an integer num. Rearrange the digits of num such that its value is minimized and it does not contain any leading zeros.

Return the rearranged number with minimal value.

Note that the sign of the number does not change after rearranging the digits.

입력: num = 310

출력: 103

내 풀이

class Solution:
    def smallestNumber(self, num: int) -> int:
	
        if num == 0:
            return 0

        num = list(str(num))
        
        if num[0] == '-':
            ans = sorted(num, reverse = True)
            ans = -int(''.join(ans[:len(ans)-1]))

        else:
            ans = sorted(num)
            if ans[0] == '0':
                for i in range(1, len(ans)):
                    if ans[i] != '0':
                        ans[i], ans[0] = ans[0], ans[i]
                        break
            ans = ''.join(ans)
            ans = int(ans)
                    
        return ans
     

결과

Runtime: 45 ms, faster than 66.23% of Python3 online submissions for Smallest Value of the Rearranged Number. Memory Usage: 13.9 MB, less than 25.70% of Python3 online submissions for Smallest Value of the Rearranged Number.

Comments