zoukankan      html  css  js  c++  java
  • 最小排列数

    题目描述:

    输入一个正整数数组,将它们连接起来排成一个数,输出能排出的所有数字中最小的一个。例如输入数组{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;
    }

    执行效果图:

  • 相关阅读:
    Flash 终将谢幕:微软将于年底( 2020 年 )停止对 Flash 的支持
    分布式id生成方案总结
    如何设计一个亿级网关(API Gateway)?
    服务之间的调用为啥不直接用 HTTP 而用 RPC?
    Dubbo 总结:关于 Dubbo 的重要知识点
    CAP理论解读
    单点登录(SSO)的设计与实现
    入职微软三个月把老板炒了,七个月自己跑路是一种怎样的体验?
    有关链表的小技巧,我都给你总结好了
    排序算法入门之「选择排序」
  • 原文地址:https://www.cnblogs.com/biyeymyhjob/p/2695637.html
Copyright © 2011-2022 走看看