整型数组中各元素拼合成最大数字问题

整型数组中各元素拼合成最大数字问题

      身边两位找工作的同学遇到了一个同样的笔试题:给定一个非负的整数数组,找出由其中的数字拼接成的最大数,如[1,23,2,6,7]找出来的数字是762321。我在网上找到一个解决方案,并且用C++实现了如下程序:

 1 #include "stdafx.h"
 2 #include <string>
 3 using namespace std;
 4 int _tmain(int argc, _TCHAR* argv[])
 5 {
 6     int a[5] = { 26, 10, 10, 35, 7};
 7     int array_length = sizeof(a) / sizeof(a[0]);//数组大小
 8     string str[5];
 9     for (int i = 0; i < 5; i++)
10     {
11         char temp[10];
12         _itoa_s(a[i], temp, 10);
13         str[i] = string(temp);
14     }
15     string temp;
16     for (int i = 0; i < array_length; i++)
17     {
18         for (int j = i + 1; j < array_length; j++)
19         {
20             string str1 = str[i] + str[j];
21             string str2 = str[j] + str[i];
22             if (str1.compare(str2) < 0)
23             {
24                 temp = str[i];
25                 str[i] = str[j];
26                 str[j] = temp;
27             }
28         }
29     }
30 
31     for (int k = 0; k < array_length; k++)
32     {
33         printf("%s", str[k].c_str());
34     }
35     getchar();
36     return 0;
37 }
原文地址:https://www.cnblogs.com/AlgrithmsRookie/p/5900683.html