Best Solution using Arrays in O(logn) | Simple Sorting and Swapping) | Beats 100%
Intuition\nThe code is designed to find the smallest number that can be formed from the digits of a given integer while considering its sign. \n\n# Approach\n1.
# Intuition\nThe code is designed to find the smallest number that can be formed from the digits of a given integer while considering its sign. \n\n# Approach\n1. It handles the special case where the input number is 0, returning 0 immediately because the smallest number with no digits is 0.\n\n2. For positive numbers, it extracts the digits from the input number and stores them in a vector n. Each digit is obtained by taking the remainder when dividing the number by 10 and then dividing the number by 10 to remove the last digit.\n\n3. If the input number is non-negative, it sorts the digits in ascending order using sort(n.begin(), n.end()). However, it also ensures that the smallest digit (non-zero) appears in the first position by performing a swap if necessary. This way, the smallest number is formed.\n\n4. For negative numbers, it sorts the digits in descending order using sort(n.begin(), n.end(), greater<int>()). This ensures that the smallest number with the given digits is formed, taking into account the negative sign.\n\n5. Finally, it constructs the smallest number by iterating through the sorted n vector and multiplying the result by 10 while adding each digit.\n\n6. The code handles both positive and negative numbers correctly and ensures that the smallest number possible with the given digits is returned.\n\n# Complexity\n- Time complexity:\nOverall, the time complexity is dominated by the sorting step, so the final time complexity is O(log(n)), where n is the number of digits in the input number.\n\n- Space complexity:\nOverall, the space complexity is O(d), where d is the number of digits in the input number.\n\n# Code\n```\nclass Solution {\npublic:\n    long long smallestNumber(long long num) {\n        if (num == 0) {\n            return 0;\n        }\n        long long temp = abs(num);\n        vector<int> n;\n        \n        while (temp != 0) {\n            int rem = temp % 10;\n            n.push_back(rem);\n            temp /= 10; \n        }\n        if (num >= 0) {\n            sort(n.begin(), n.end());\n            if (n[0] == 0) {\n                for (int i = 1; i < n.size(); i++) {\n                    if (n[i] != 0) {\n                        swap(n[0], n[i]);\n                        break;\n                    }\n                }\n            }\n        } else {\n            sort(n.begin(), n.end(), greater<int>());\n        }\n        long long result = 0;\n        for (int digit : n) {\n            result = result * 10 + digit;\n        }\n        return (num >= 0) ? result : -result;\n    }\n};\n```
['Array', 'Sorting', 'C++']