首页 > 代码库 > 把数组排成最小的数

把数组排成最小的数

bool com( const string& a, const string& b )
{
    string A;
    A.append( a );
    A.append( b );
    string B;
    B.append( b );
    B.append( a );
    
    int i = 0;
    while( A[i] == B[i] )
    {
        i++;
    }

    return A[i] < B[i];
}

string PrintMinNumber(vector<int> numbers)
{
    string res = "";
    vector< string > snumbers;
    char num[ 10 ];
    string snum;
    for( int i = 0; i < numbers.size(); i++ )
    {
        sprintf( num, "%d", numbers[i] );
        snum = num; //snum.length()为实际字符长度
        snumbers.push_back( snum );
    }

    //默认用string的compare函数,字符串比较, "3" < "32" < "321",但与题不符
    //sort默认升序排序
    //sort( snumbers.begin(), snumbers.end() );

    sort( snumbers.begin(), snumbers.end(), com );

    for( int i = 0; i < snumbers.size(); i++ )
    {
        //cout << snumbers[i];
        res += snumbers[i];
    }
        //cout << endl;
    return res;
}

 

把数组排成最小的数