题目要求:
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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
在博文Leetcode:Largest Number详细题解有相对详细的分析,但本文没有参考其做法,而是参考了LeetCode论坛上的一个解决方法。具体程序如下:
1 class Solution { 2 public: 3 static bool com(const int & m, const int & n) 4 { 5 return to_string(m) + to_string(n) > to_string(n) + to_string(m); 6 } 7 8 string largestNumber(vector<int>& nums) { 9 string ret; 10 sort(nums.begin(), nums.end(), com); 11 12 int sz = nums.size(); 13 if(sz != 0 && nums[0] == 0) 14 return "0"; 15 16 for(int i = 0; i < sz; i++) 17 ret += to_string(nums[i]); 18 19 return ret; 20 } 21 };
这里边值得一提的就是字符串大小比较的原理:
字符串的大小比较是逐个相应字符进行比较(比较他们的ASCII码),直到有两个字符不相等为止,ASCII码大的字母所在字符串就大,与字符串长度无关。对两个相等长度的字符串,若每个字符都比较完毕后仍相等,则两字符串相等;对不等长的字符串,若当短的字符串比较完毕时所有字符仍相等,则长度较长的字符串大!