剑指offer 45-把数组排成最小的数

核心方案:排序,对自制cmp排序规则,确定那个数排在前面。

  • 关键:to_string 函数,是basic_string库的一个函数,把整数或者浮点数转换成字符串。此库主要包含的函数:字符串转其它与其它转成字符串!http://classfoo.com/ccby/article/PMZdbE#sec_hMZ6te
  • 当然也可用之前就学会的stringstream来进行转换: (需要include ) 语法上stringstream 类型的变量都在左侧
stringstream ss;
ss<
ss.str(str1);
ss.put(' st');
ss<> i;
  • 此题代码
class Solution {
    static bool cmp(int a, int b){ // 谓词函数需要时static型的!输入参数更好是const string &a 
        string str1="";
        string str2="";
        str1+=to_string(a);
        str1+=to_string(b);
        str2+=to_string(b);
        str2+=to_string(a);
        return str1 numbers) {
        //if(numbers.size()==0)
            //return 0;   //加了这一项编译不通过,不知道为什么
        if(numbers.size()==1)
            return to_string(numbers[0]);
        string output="";
        sort(numbers.begin(),numbers.end(),cmp);
        for(int i=0;i

你可能感兴趣的:(剑指offer 45-把数组排成最小的数)