Arrange given numbers to form the biggest number?

CServer Side ProgrammingProgramming

Here we will see how to generate the biggest number by rearranging the given numbers. Suppose there are {45, 74, 23} is given, the program will find the largest number, that is 744523. So each digit will not be arranged. but the whole number will be placed to make largest number.

To solve this problem, we will use the string sorting. But the comparison logic is different. The comparing function will take two numbers a and b, then concatenate them to form ab and ba. Among them which one is bigger, that is considered.

Algorithm

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

Example

 Live Demo

#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);
}

Output

744523
raja
Published on 26-Jul-2019 10:59:39
Advertisements