Created
December 12, 2019 07:34
-
-
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.
This file contains hidden or 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
| /* 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