C++ solution | Beats 100% ✅ | TC: O(N)
Easy C++ code with explanation:\nAs, we need to rearrange the digits to form the smallest possible numbers, the most eficiient way would be to convert it to str
# Easy C++ code with explanation:\nAs, we need to rearrange the digits to form the smallest possible numbers, the most eficiient way would be to convert it to string. So,\n1. First, we check if the number starts with a negative sign \'-\' and resize the string excluding the first index.\n2. We create a frequency array to count the occurences of every digit.\n3. Now, we have to add the digits to create the smallest possible number.\n\nFor this, there will be 2 cases - \n1. If the number is negative:\n* We have to create the largest number. \n* For this, we will be traversing the array from the end and adding the available digits in descending order. \n\nFor negative:\n\n\tfor(int i = 9; i>0; i--) {\n                while(v[i]--) {\n                    ans += to_string(i);\n                }\n            }\n\n2. When the number is positive:\n* \tAs, we don\'t want any leading zeroes, we will start traversing from index \'1\' and when count[i] > 0, we will add this to the ans and reduce the count by 1.\n* \tThen add all the remaining digits in the ascending order of indexes.\n\t\t\t\t\nFor positive \n\n\tfor(int i = 1; i<10; i++) {\n                if(v[i] > 0) {\n                    v[i]--;\n                    ans += to_string(i);\n                    break;\n                }\n            }\n            for(int i = 0; i<10; i++) {\n                while(v[i]--) {\n                    ans += to_string(i);\n                }\n            }\n\t\t\t\nHere is the final code with appropriate comments:\n\n    long long smallestNumber(long long num) {\n        string ans = "";\n        vector<int> v(10);\n        // convert the integer to string\n        string s = to_string(num);\n        \n        // check if the number is negative\n        bool neg = false;\n        if(s[0] == \'-\') {\n            neg = true;\n            s = s.substr(1, s.size()-1);\n        }\n\n        for(long long i = 0; i<s.size(); i++) {\n            v[s[i]-\'0\']++;\n        }\n        \n        // for negative integer\n        if(neg) {\n            ans = "-";\n            for(int i = 9; i>=0; i--) {\n                while(v[i]--) {\n                    ans += to_string(i);\n                }\n            }\n        }\n        \n        // for positive integer\n        else {\n            for(int i = 1; i<10; i++) {\n                if(v[i] > 0) {\n                    v[i]--;\n                    ans += to_string(i);\n                    break;\n                }\n            }\n            for(int i = 0; i<10; i++) {\n                while(v[i]--) {\n                    ans += to_string(i);\n                }\n            } \n        }\n\t\treturn stoll(ans);\n    }
['String', 'C', 'Sorting', 'C++']