Given a list of non-negative integers, I have to arrange them such that they form the largest number and return the number as a string.
Input is[3, 30, 34, 5, 9]. I tried to traverse the array manually but I didn't understand where I was wrong. All the elements are swapped as I expected but 3 and 30 didn't get swapped. Could anyone please find the error in the code?
#include <iostream>
#include <vector>
using namespace std;
int main()
{vector<int>A={ 3, 30, 34, 5, 9 };
vector<int>b;b.assign(A.begin(),A.end());
for(int i=0;i<b.size()-1;i++){
for(int j=i+1;j<b.size();j++){
string str1,str2,str3,str4;
str1=to_string(A[i]);
str2=to_string(A[j]);
str3=str1.append(str2);
str4=str2.append(str1);
if(stoi(str4)>stoi(str3)){
swap(b[i],b[j]);
}
}
}
string s="";
for(int i=0;i<A.size();i++){
s.append(to_string(b[i]));
}
cout<<s;
return 0;
}
Expected 9534330
Actual 9534303
Aucun commentaire:
Enregistrer un commentaire