How to find the largest number formed from an array of numbers
Problem statement
Assume we are given an array of non-negative integers, and we need to arrange the numbers in such a way that they form the largest possible number.
Sample input | Output |
[10, 7, 9, 2, 3] | 973210 |
[4, 6, 8, 2, 3] | 86432 |
For this purpose, we need to write a function findMaxNum that takes an integer array arr and its size n as input.
int findMaxNum(int arr[], int n);
This function should return the largest number that can be formed from the given array as an integer.
Code example
In this code, we aim to find the largest possible number that can be formed by concatenating the given array of numbers. The code utilizes a custom comparison function and sorting algorithm to arrange the numbers to maximize the resulting value. Let's take a look at the implementation.
#include <iostream>#include <algorithm>#include <string>using namespace std;bool compareNumbers(int a, int b){string num1 = to_string(a);string num2 = to_string(b);return (num1 + num2) > (num2 + num1);}int findMaxNum(int arr[], int n){sort(arr, arr + n, compareNumbers);string largestNumStr = "";for (int i = 0; i < n; i++){largestNumStr += to_string(arr[i]);}return stoi(largestNumStr);}int main(){int arr[] = {10, 7, 9, 2, 3};int n = sizeof(arr) / sizeof(arr[0]);int largestNumber = findMaxNum(arr, n);cout << "Largest Number: " << largestNumber << endl;return 0;}
Explanation
Now, let's take a closer look at the C++ code and understand its workings in depth.
Lines 7-12:
compareNumbersfunction takes two integers as input arguments and compares them by converting them to strings and concatenating them.Lines 9-10: Converts the integer
aand integerbto a string using theto_stringfunction from the string library.Line 11: Compares the concatenation of
num1andnum2with the concatenation ofnum2andnum1and returnstrueif the first concatenation is greater than the second concatenation, andfalseotherwise.Line 15:
findMaxNumtakes an array of integersarrand its sizenas input.Line 17: Sorts the array
arrin descending order using thecompareNumberscustom comparison function.Line 19: Initializes an empty string named
largestNumStr.Line 22: This line converts each element of the array to a string and appends it to the
largestNumStrstring.Line 25: This line converts the
largestNumStrstring to an integer using thestoifunction and returns it.
Free Resources