Last active
August 29, 2015 13:55
-
-
Save sundeepblue/8703656 to your computer and use it in GitHub Desktop.
arrange array to form a smallest number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bool comp(string s1, string s2) { | |
if((s1+s2).compare(s2+s1) < 0) return true; | |
return false; | |
} | |
// cannot handle the case when exist 0 | |
string get_smallest_number(vector<int> &nums) { | |
if(nums.empty()) return ""; | |
string res = ""; | |
vector<string> strs; | |
for(int i=0; i<nums.size(); i++) | |
strs.push_back(to_string(nums[i])); | |
sort(strs.begin(), strs.end(), comp); | |
for(int i=0; i<strs.size(); i++) res += strs[i]; | |
return res; | |
} | |
// can handle "0" in array | |
string get_smallest_number(vector<int> &nums) { | |
if(nums.empty()) return ""; | |
string res = ""; | |
int num_zeros = 0; | |
vector<string> strs; | |
for(int d : nums) { | |
if(d == 0) num_zeros++; | |
else strs.push_back(to_string(d)); | |
} | |
sort(strs.begin(), strs.end(), comp); | |
for(string& s : strs) res += s; | |
string zeros; | |
for(int i=0; i<num_zeros; i++) zeros += '0'; | |
return res.substr(0, 1) + zeros + res.substr(1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment