码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]Largest Number

时间:2015-01-24 14:29:39      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

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.

Note: The result may be very large, so you need to return a string instead of an integer.

bool cmp(const string a, const string b){
      return (a+b) > (b+a);
}
class Solution {
public:

    string tostring(int x){
      if(x == 0) return "0";
      string tmp = "";
      while(x){
        tmp = (char)(x%10+'0') + tmp;
        x /= 10;
      }
      return tmp;
    }
    vector<string>s;
    string largestNumber(vector<int> &num) {
        for(int i = 0; i < num.size(); i++)
            s.push_back(tostring(num[i]));
        sort(s.begin(),s.end(),cmp);
        string ans = "";
        for(int i = 0; i < s.size(); i++)
          if(ans != "" || s[i] != "0")
              ans += s[i];
        return ans == "" ? "0" : ans;
    }
};


[leetcode]Largest Number

标签:

原文地址:http://blog.csdn.net/sina012345/article/details/43085053

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!