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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

  1. string to_convert(int a) {
  2. stringstream ss;
  3. ss << a;
  4. string tmp;
  5. ss >> tmp;
  6. ss.clear();
  7. ss.str("");
  8. return tmp;
  9. }
  10. bool cmp(int a,int b) {
  11. string tmp1 = to_convert(a);
  12. string tmp2 = to_convert(b);
  13. string first = tmp1 + tmp2;
  14. string second = tmp2 + tmp1;
  15. return first>second;
  16. }
  17. class Solution {
  18. public:
  19. string largestNumber(vector<int> &num) {
  20. sort(num.begin(),num.end(),cmp);
  21. string result = "";
  22. for(int i=0;i<num.size();i++) {
  23. result += to_convert(num[i]);
  24. }
  25. int pos=0;
  26. while(pos<result.size()-1 && result[pos] == '0') pos++;
  27. result = result.substr(pos);
  28. return result;
  29. }
  30. };

 

处理对象转换思路更好些

posted @ 2015-01-13 23:06  purejade  阅读(109)  评论(0)    收藏  举报