goyalsaransh002
goyalsaransh002

Reputation: 15

largest number. Given a list of non negative integers, arrange them such that they form the largest number

Why is this code giving the wrong output?

Question: 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.

This is my code:

bool compareinterval(int x,int y);
string Solution::largestNumber(const vector<int> &A) 
{
    //sort(A.begin(),A.end());
    vector< int>B;
    int i,x=0;
    for(i=0;i<A.size();i++)
       B.push_back(A[i]);
    sort(B.begin(),B.end(),compareinterval);
    vector<string> vect;

string result;

    for(i=0;i<B.size();i++)
    {

      ostringstream convert;
    convert<<B[i];
    if(B[i]!=0)
       x=1;

    string str1=convert.str();
        result.append(str1);
    }
   if(x==0)
      return "0";
    else
     return result;

}
bool compareinterval(int x,int y)
{
    ostringstream convert;
    string result;
    convert<<x;
    string str1=convert.str();
     //ostringstream convert;
    //string result;
   // ostringstream convert;
    convert<<y;
    string str2=convert.str();
    int i;




    for(i=0;i<min(str1.length(),str2.length());i++)
    {
        if((str1[i]-'0')<(str2[i]-'0'))  
           return false;
         if((str1[i]-'0')>(str2[i]-'0'))  
           return true;


    }
    //return true;
    if(str1.length()<str2.length())
       return true;
else
    return false;



}

This is the input and output:

input:A : [ 9, 99, 999, 9999, 9998 ]
my output:999899999999

I have defined compare function which is not working properly .

Can someone correct it?

Upvotes: 0

Views: 1910

Answers (2)

code707
code707

Reputation: 1701

Issue is that:

    convert<<x;
    string str1=convert.str();

    convert<<y;
    string str2=convert.str();

you are appending second integer to first integer. For example, if x is 9, y is 8, str1 will be 9 and str2 will be 98. That is NOT what you wanted. Instead use separate variables (or reset stringstream before reusing)

    convert1<<x;
    string str1=convert1.str();

    convert2<<y;
    string str2=convert2.str();

This should make things work.

Upvotes: 0

Superman
Superman

Reputation: 309

This is what comes to mind.

  1. Convert all input to string - 10 to "10"
  2. Use std::sort to arrange strings in descending order. You could use a custom compare method or strcmp perhaps.
  3. Now simply concatenate the rearranged strings.

Upvotes: 1

Related Questions