Largest Number - C++ Solution

1. Introduction

This blog post discusses an intriguing problem in array and string manipulation: creating the largest number possible by arranging a set of numbers. This problem requires an understanding of sorting algorithms and custom comparison functions in C++.

Problem

Given a set of numbers, the challenge is to arrange them in such a way that by concatenating them, they form the largest possible number. The solution should return the string representation of this largest number.

Example:

Input: [10, 68, 75, 7, 21, 12]

Output: 77568211210

2. Solution Steps

1. Convert the integers in the array to strings.

2. Sort the strings using a custom comparator that orders them by the value of their concatenation.

3. Concatenate the sorted strings.

4. Return the concatenated result as the largest number.

3. Code Program

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;

// Custom comparator for sorting
bool compareNumbers(string &a, string &b) {
    return a + b > b + a;
}

// Function to find the largest number
string largestNumber(vector<int>& nums) {
    vector<string> numStrs;
    for (int num : nums) {
        numStrs.push_back(to_string(num));
    }

    // Sort using the custom comparator
    sort(numStrs.begin(), numStrs.end(), compareNumbers);

    // Concatenate the sorted strings
    string result;
    for (string &s : numStrs) {
        result += s;
    }

    // Handle the case of numbers starting with zero
    if (result[0] == '0') {
        return "0";
    }

    return result;
}

int main() {
    vector<int> nums = {10, 68, 75, 7, 21, 12};
    cout << "Largest Number: " << largestNumber(nums) << endl;
    return 0;
}

Output:

Largest Number: 77568211210

Explanation:

The largestNumber function first converts the integers to strings. It then sorts these strings using a custom comparator, which orders them based on the value of their concatenation. After sorting, the function concatenates these strings to form the largest number. Special handling is added to account for numbers starting with zero. This approach ensures that the output is the largest possible number formed by the concatenation of the given numbers.


Comments