Efficient approach | Sort and Swap | CPP
\n\n# Approach\n Describe your approach to solving the problem. \nBrute Force :-\nRecursively generate all the permutations and store it in a data structure, di
\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBrute Force :-\nRecursively generate all the permutations and store it in a data structure, discard the values which have leading zeros . Find minimum value amongst the remaining values.\nThe constraints are 10^15 so the complexity in generating permutations will be O(15!) that will be a tle for sure.\n\nOptimized approach :-\nType cast the number into a string. If the number is positive sort the string in increasing order. If first index is 0 then swap the first index with the first non-zero index.\nIf it is a negative number sort it in decreasing order. \nconvert it in long long and return the ans.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(nlogn)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n    long long smallestNumber(long long num) {\n        string s = to_string(abs(num));\n        if(num >= 0){\n            sort(s.begin() , s.end());\n            \n        }\n        else{\n            sort(s.begin() , s.end() , greater < int > ());\n        }\n        if(num > 0){\n            int index = s.find_first_not_of(\'0\');\n            swap(s[0] , s[index]);\n\n        }\n        long long ans = stoll(s);\n        if(num < 0){\n            ans *= -1;\n        \n        }\n        return ans;\n    }\n};\n```
['C++']