C++ Basic Solution with explanation using comments


#1

bool comp(int& a,int& b){
string a1,b1;
a1 = to_string(a);
b1 = to_string(b);
return (a1+b1)>(b1+a1);
}

string Solution::largestNumber(const vector &A) {
if(A.size()==0){
return “”;
}else if(A.size()==1){
return to_string(A[0]);
}

bool z=false;  //FOR CASE WHEN EACH ELEMENT IN ZERO
for(int i=0;i<A.size();i++){
    if(A[i]!=0){
        z=true;
        break;
    }
}
if(z==false) return "0";

vector<int> b;       // making another vector as A is declared as const
for(int i=0;i<A.size();i++) b.push_back(A[i]);
string ans="";
sort(b.begin(),b.end(),comp);    // sorting using own comparator function 
for(int i=0;i<b.size();i++){
    ans+= to_string(b[i]);
}
return ans;

}