Last active
July 12, 2021 08:16
-
-
Save cruxrebels/932117c5f848b2fb5746e5c6d218164d 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. 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. Tags: InterviewBit Arrays Problem https://www.interviewbit.com/problems/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
bool myCompare(const int x, const int y) | |
{ | |
auto tempx = x; | |
auto tempy = y; | |
auto cx = 0; | |
auto cy = 0; | |
while(tempx!=0 || tempy!=0) | |
{ | |
if(tempx!=0) | |
{ | |
tempx /= 10; | |
++cx; | |
} | |
if(tempy!=0) | |
{ | |
tempy /= 10; | |
++cy; | |
} | |
} | |
auto xy = (x*(pow(10, cy)))+y; | |
auto yx = (y*(pow(10, cx)))+x; | |
//cout << xy << "\t" << yx << "\t" << x << "\t" << y << "\n"; | |
return (xy>yx); | |
} | |
string Solution::largestNumber(const vector<int> &A) { | |
vector<int> B; | |
int c = 0; | |
stringstream r; | |
r << 0; | |
for(auto const& a : A) | |
{ | |
B.emplace_back(a); | |
if (a==0) | |
++c; | |
} | |
if (c==A.size()) | |
return r.str(); | |
sort(B.begin(), B.end(), myCompare); | |
stringstream result; | |
for(const auto& b : B) | |
result << b; | |
//copy(B.begin(), B.end(), ostream_iterator<int>(result, "")); | |
return result.str(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment