每天编程1

2016-03-24

存在n个正整数,设计一个算法,按照一定的顺序将这n个数排列起来,使得连接起来的数最大,输出这个数。

例如,输入[5, 92. 8],,输出为9285;

注意:

 1 #include "stdafx.h"
 2 #include <iostream>
 3 #include <sstream>
 4 #include <vector>
 5 #include <algorithm>
 6 using namespace std;
 7 
 8 bool Compare(const string & s1, const string& s2)
 9 {
10     return (s1 + s2) > ( s2 + s1);
11 }
12 
13 string intTostr(int n)
14 {
15     if (n == 0)
16         return "0";
17     string str;
18     while (n)
19     {
20         str = char(n % 10 + '0') + str;
21         n = n / 10;
22     }
23     return str;
24 }
25 
26 
27     string largestNumber(vector<int> vec)
28     {
29         if (vec.size() == 0)
30             return "";
31         vector<string> val(vec.size());
32         stringstream stream;
33         for (int i = 0; i < vec.size(); ++i)
34             val[i] = intTostr(vec[i]);
35         sort(val.begin(), val.end(), Compare);
36         string sum;
37         for (int i = 0; i < val.size(); ++i)
38             sum = sum + val[i];
39         if (sum[0] == '0')
40             return "0";
41         return sum;
42     }
43 
44 int main()
45 {
46     vector<int> vec1{ 1, 2, 3 };
47     vector<int> vec2{ 3, 4, 5};
48     cout << largestNumber(vec1) << endl;
49     return 0;
50 }
View Code

 

posted @ 2016-03-24 20:11  秋雨寒破春泥  Views(139)  Comments(0)    收藏  举报