【leetcode】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.

 

设a有x位,b有y位
如果a排在前面,则
a*10^y+b>b*10^x+a
 
利用该思想进行排序
 1 class Solution {

 2 public:

 3  

 4     static bool cmp(int a,int b)

 5     {

 6         int digitA=1;

 7         int digitB=1;

 8        

 9         int tmpA=a;

10        

11         while(tmpA>=10)

12         {

13             digitA++;

14             tmpA/=10;

15         }

16        

17         int tmpB=b;

18         while(tmpB>=10)

19         {

20             digitB++;

21             tmpB/=10;

22         }

23        

24         return a*pow(10,digitB)+b>b*pow(10,digitA)+a;

25        

26     }

27  

28     string largestNumber(vector<int> &num) {

29        

30         sort(num.begin(),num.end(),cmp);

31        

32         string result="";

33        

34         for(int i=0;i<num.size();i++)  

35         {

36             result+=to_string(num[i]);

37         }

38        

39         if(result[0]=='0') result="0";

40        

41         return result;

42        

43     }

44 };

 

另一种方法,先把数字转化为字符串,然后通过字符串拼接去比较,这样cmp函数会好些很多

  

 

 1 class Solution {

 2 public:

 3 

 4     static bool cmp(string a,string b)

 5     {

 6         return a+b>b+a;

 7     }

 8 

 9     string largestNumber(vector<int> &num) {

10         

11         int n=num.size();

12         vector<string> strNum(n);

13         for(int i=0;i<n;i++)

14         {

15             strNum[i]=to_string(num[i]);

16         }

17         

18         sort(strNum.begin(),strNum.end(),cmp);

19         

20         string result="";

21         

22         for(int i=0;i<n;i++)

23         {

24             result+=strNum[i];

25         }

26         

27         if(result[0]=='0') result="0";

28         

29         return result;

30     }

31 };

 

 

你可能感兴趣的:(LeetCode)