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

leetcode[179]Largest Number

时间:2015-02-09 00:37:33      阅读:218      评论: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.

对于每两个数字所能组成的字符串进行大小排序,然后顺序输出,注意0的特殊处理。

bool com(string a,string b)
{
    return (a+b)>(b+a);
}

class Solution {
public:
string  to_str(long long  n)
{
    string str="";
    if(n==0)
    {
        str+=0;
        return str;
    }
    long long tmp=n;
    long long power=1;
    int icount=0;
    while (tmp)
    {
        tmp/=10;
        power*=10;
        icount++;
    }
    power/=10;
    tmp=n;
    for (int i=0;i<icount;i++)
    {
        long long d=tmp/power;
        str+=char(0+d);
        tmp-=d*power;
        power/=10;
    }
    return str;
}
    string largestNumber(vector<int> &num) {
      if(num.empty())return "";
      int n=num.size(); 
      vector<string> str;
      for(int i=0;i<n;i++)
      {
          str.push_back(to_str(num[i]));
      }
      sort(str.begin(),str.end(),com);
      string res="";
      for(int i=0;i<n;i++)
      {
          if(str[i]!="0")res+=str[i];
          else
          {
              if(res!="")res+=str[i];
          }
      }
      if(res=="")res+="0";
      return res;
    }
};

 

leetcode[179]Largest Number

标签:

原文地址:http://www.cnblogs.com/Vae98Scilence/p/4280637.html

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