排列给定数字以形成最大数字?

在这里,我们将看到如何通过重新排列给定的数字来生成最大的数字。假设给出了{45,74,23},程序将找到最大的数字,即744523。因此,将不排列每个数字。但整个数字将成为最大的数字。

为了解决这个问题,我们将使用字符串排序。但是比较逻辑是不同的。比较函数将取两个数字a和b,然后将它们连接起来形成ab和ba。其中一个较大,即被考虑。

算法

compareStrings(a,b)

begin
   ab := concatenate b with a
   ba := concatenate a with b
   compare ba with ab, then return 1 if ba is bigger, otherwise return 0
end
getLargest(arr):
begin
   sort the arr with the comparison logic using compareString()   for each string s in arr, do
      print s
   done
end

示例

#include<iostream>
#include <string>
#include &t;vector>
#include <algorithm>
using namespace std;
int stringCompare(string a, string b) {
   string ab = a.append(b);
   string ba = b.append(a);
   return ab.compare(ba) > 0 ? 1: 0;
}
void getLargest(vector<string> arr) {
   sort(arr.begin(), arr.end(), stringCompare); //sort the array
   for (int i =0; i < arr.size() ; i++ )
      cout << arr[i];
}
int main() {
   vector<string> arr;
   arr.push_back("45");
   arr.push_back("74");
   arr.push_back("23");
   getLargest(arr);
}

输出结果

744523