Skip to content

Instantly share code, notes, and snippets.

@sr6033
Created December 12, 2019 07:34
Show Gist options
  • Select an option

  • Save sr6033/0465d5fee12d13ce4e79331af44fe457 to your computer and use it in GitHub Desktop.

Select an option

Save sr6033/0465d5fee12d13ce4e79331af44fe457 to your computer and use it in GitHub Desktop.
Given a list of non negative integers, arrange them such that they form the largest number.
/* https://www.interviewbit.com/problems/largest-number/
Given a list of non negative integers, arrange them such that they form the largest number.
For example:
Given [3, 30, 34, 5, 9], the largest formed number is 9534330.
Note: The result may be very large, so you need to return a string instead of an integer.
*/
bool compare(string s1, string s2)
{
string s1s2 = s1 + s2;
string s2s1 = s2 + s1;
return s1s2 > s2s1;
}
string largestNumberPossible(const vector<int> &A) {
vector<string> arr;
string ans = "";
for(int i = 0; i < A.size(); i++)
{
string s = to_string(A[i]);
arr.push_back(s);
}
sort(arr.begin(), arr.end(), compare);
for(auto i = arr.begin(); i != arr.end(); i++)
ans += *i;
int count = 0;
for(int i = 0; i < ans.length(); i++)
{
if(count == ans.length()-1)
{
ans = ans.substr(0, 1);
break;
}
else
if(ans[i] == '0')
{
count++;
continue;
}
else
{
ans = ans.substr(i, ans.length());
break;
}
}
return ans;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment