leetcode_num179_Largest Number

时间:2015-04-01 19:58:45   收藏:0   阅读:235

Given a list of non negative integers, arrange them such that they form the largest number.

For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.

两两比较 可以利用sort函数来排序,自定义compare函数,即比较规则

可用vector来代替数组,容易定位

bool compare(int a,int b){
    string t1=to_string(a)+to_string(b);
    string t2=to_string(b)+to_string(a);
    return t1>t2;
}
    //return to_string(a)+to_string(b)>to_string(b)+to_string(a);
    
class Solution {
public:
    string largestNumber(vector<int> &num) {//use vector to present array
        if(num.size()<=0)
            return "";
        sort(num.begin(),num.end(),compare);
        string res;
        for(int i=0;i<num.size();i++)
            res+=to_string(num[i]);
        return res[0]=='0'?"0":res;//only elements valued 0
    }
};


原文:http://blog.csdn.net/eliza1130/article/details/44811613

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!