---
# System prepended metadata

title: 2165. Smallest Value of the Rearranged Number
tags: [Leetcode, Sorting, Medium]

---

# 2165. Smallest Value of the Rearranged Number
###### tags: `Leetcode` `Medium` `Sorting`
Link: https://leetcode.com/problems/smallest-value-of-the-rearranged-number/description/
## 思路
如果num是负数 把各个位从大到小排序 加上负号输出即可
如果num是正数 从小到大排序 找到第一个不是0的位 然后和第一位交换
## Code
```python=
class Solution:
    def smallestNumber(self, num: int) -> int:
        s = sorted(str(abs(num)))
        if num<0:
            return -int(''.join(s[::-1]))
        i = next((i for i, a in enumerate(s) if a!="0"), 0)
        s[i], s[0] = s[0], s[i]
        return int(''.join(s))
```