笔试编程——把数组排成最小的数

题目:

输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。

思考:

自己对C++中封装好的许多函数都不是很了解,起初看到这个题目的时候,觉得这个程序做起来代码量有点大,需要拆解每一个数,又要对拆解好的数进行比较,根据一定的规则进行排序。在看了别人写的范例程序之后,大吃一惊,sort函数 和 to_string函数,简单的几句话,就把我认为复杂的步骤完成了。

sort函数:

需要头文件<algorithm>

语法描述:sort(begin,end,cmp),cmp参数可以没有,如果没有默认非降序排序。

to_string函数,可以实现整数到字符串的转换。

class Solution {
public:
    string PrintMinNumber(vector<int> numbers) {
        int len = numbers.size();
        sort(numbers.begin(), numbers.end(), cmp);
        string ans;
        for(int i = 0; i < len; i++) {
            ans += to_string(numbers[i]);
        }
        return ans;
    }
     
    static bool cmp(int a, int b) {
        string A = to_string(a) + to_string(b);
        string B = to_string(b) + to_string(a);
        return A < B;
    }
};

猜你喜欢

转载自blog.csdn.net/CSDN_JKing/article/details/81393231