DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

1 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.

Example 1:

Input: num = 310
Output: 103
Explanation: The possible arrangements for the digits of 310 are 013, 031, 103, 130, 301, 310.
The arrangement with the smallest value that does not contain any leading zeros is 103.

Example 2:

Input: num = -7605
Output: -7650
Explanation: Some possible arrangements for the digits of -7605 are -7650, -6705, -5076, -0567.
The arrangement with the smallest value that does not contain any leading zeros is -7650.

Constraints:

  • -1015 <= num <= 1015

SOLUTION:

class Solution:
    def smallestNumber(self, num: int) -> int:
        if num == 0:
            return num
        negative = num < 0
        num = abs(num)
        num = list(str(num))
        if negative:
            return -int("".join(sorted(num, reverse = True)))
        minDigit = min(d for d in num if d != "0")
        num.remove(minDigit)
        return int(minDigit + "".join(sorted(num)))
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay