【LeetCode #179】Largest Number 解题报告

原题链接:Largest Number

题目描述:
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.

Solution:

  • 易忽略全为0的情况
  • 字符串比较算法
  • tostring()的运用
  • sort函数

代码:

class Solution
{
    public:
    //比较函数
    static bool compare(string s1, string s2)
    {
        return (s1 + s2) > (s2 + s1);
    }

    string largestNumber(vector<int>& nums) 
    {
        if(nums.empty())
            return "";

        vector<string> strNums;

        vector<int>::const_iterator iter = nums.begin();
        while (iter != nums.end())
        {
            //把整形转换成字符串类型
            strNums.push_back(to_string((long long)*iter));
            iter ++;
        }

        //借用sort函数对转换后的数字字符串排序
        sort(strNums.begin(), strNums.end(),compare);

        string res = "";
        vector<string>::const_iterator it = strNums.begin();
        while(it != strNums.end())
        {
            res.append(*it);
            it ++;
        }

        //输入的非负整数全部为0的情况下,输出一个0
        int index = 0;
        while (index < res.length() && res[index] == '0')
            index ++;

        if (index == res.length())
            return "0";

        return res;
    }
};
原文地址:https://www.cnblogs.com/lanqiu5ge/p/9472215.html