最小排列数

题目描述:

输入一个正整数数组,将它们连接起来排成一个数,输出能排出的所有数字中最小的一个。例如输入数组{32,  321},则输出这两个能排成的最小数字32132。请给出解决问题的算法,并证明该算法。

 

解析:

对数组进行排序,排序规则:当两个数进行比较时,现将他们转坏为char数组,然后用两个char指针挨个字符进行比较,当其中一个为正常字符,而另一个为‘\0’,则后者指针回溯第一个字符,直到找到第一个不相同的字符,字符大者的对应数为大,或者当两者指针对应字符皆为‘\0’时,此时证明两个数字”相等“。具体实现,见下面参考代码:

 

参考代码:

#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>

using namespace std;


void itoa(int number,char *str)
{
     char ch[100],*p=str;
     int sign=1,i;

     if(number<0)
     {
          sign=-1;
          number=-number;
     }

     for(i=0;number!=0;number/=10,i++)
     {
          ch[i]=number%10 + '0';
     }

     if(sign==-1)
          *p='-';
     i--;
     for(;i>=0;i--,p++)
          *p=ch[i];

     *p='\0';
}


bool cmp(const int a, const int b)
{
    char c1[100], c2[100];
    itoa(a, c1);
    itoa(b, c2);


    for(char *p = c1, *q = c2; *p != '\0' || *q != '\0' ; )
    {

        if(*p == '\0' && *q != '\0')
        {
            p = c1;
            continue;
        }
        else if(*q == '\0' && *p != '\0')
        {
            q = c2;
            continue;
        }

        if(*p != *q)
        {
            return (*p > *q);
        }
        p++,q++;
    }

    return false;
}

int count(int a)
{
    int i = 1;
    while(a/10 != 0)
    {
        a /= 10;
        i++;
    }

    return i;
}

int main()
{
    vector<int> num;

    int d = 0;
    do
    {
        cout << "input data: if over input 0" << endl;
        cin >> d;

        if(d == 0) break;

        num.push_back(d);
    }while(1);

    sort(num.begin(), num.end(), cmp);


    long int result = 0;
    for(vector<int>::iterator iter = num.begin() ; iter != num.end() ; iter++)
    {
        result += *iter * pow(10, count(result));
    }

    cout << endl << "the result is :";
    cout << result/10 << endl;

    return 0;
}

 

执行效果图:

posted on 2012-09-23 15:54  as_  阅读(1600)  评论(0编辑  收藏  举报

导航