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.
解题思路:string intToString(int a){ string s = ""; stack<char> stack; while (a != 0){ stack.push('0' + a%10); a /= 10; } while (!stack.empty()){ s += stack.top(); stack.pop(); } return s==""? "0":s; } //a是否字符串大于等于b bool compareGreater(int a, int b){ string sa = intToString(a), sb = intToString(b); string s1 = sa + sb; string s2 = sb + sa; return s1 > s2 ? true : false; } class Solution { public: string largestNumber(vector<int> &num) { std::sort(num.begin(), num.end(), compareGreater); int len = num.size(); if(len==0 || num[0]==0){ return "0"; } string result = ""; for (int i = 0; i<len; i++){ result += intToString(num[i]); } return result; } };
原文地址:http://blog.csdn.net/kangrydotnet/article/details/44983935