剑指Offer31 把数组排成最小的数

 1 /*************************************************************************
 2     > File Name: 31_SortArrayMin.cpp
 3     > Author: Juntaran
 4     > Mail: JuntaranMail@gmail.com
 5     > Created Time: 2016年09月02日 星期五 11时10分42秒
 6  ************************************************************************/
 7 
 8 #include <stdio.h>
 9 #include <string>
10 #include <bits/stdc++.h>
11 
12 using namespace std;
13 
14 string itos(int x)
15 {
16     return (x>9 ? itos(x/10) : "") + char(x%10 + '0');
17 }
18 
19 // qsort比较函数
20 int cmp(const void *a, const void *b)
21 {
22     return *(int*)a - *(int*)b;
23 }
24 
25 // sort比较函数
26 bool compare(int a, int b)
27 {
28     return (itos(a) + itos(b)) < (itos(b) + itos(a));
29 }
30 
31 string PrintMinNumber(int* nums, int length)
32 {
33     string s = "";
34     if (nums==NULL || length<=0)
35         return s;
36     // sort(nums, nums+length, compare);
37     qsort(nums, length, sizeof(int), cmp);
38     
39     for (int i = 0; i < length; ++i)
40         s += itos(nums[i]);
41     cout << s << endl;
42     return s;
43 }
44 
45 int main()
46 {
47     int nums[] = {3, 32, 321};
48     int length = 3;
49     PrintMinNumber(nums, length);
50     
51     return 0;
52 }
原文地址:https://www.cnblogs.com/Juntaran/p/5835659.html