sundeepblue
1/30/2014 - 6:32 AM

arrange array to form a smallest number

arrange array to form a smallest number

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);
}