Largest Number Problem


Description

LeetCode Problem 179.

Given a list of non-negative integers nums, arrange them such that they form the largest number. Note: The result may be very large, so you need to return a string instead of an integer.

Example 1:

1
2
Input: nums = [10,2]
Output: "210"

Example 2:

1
2
Input: nums = [3,30,34,5,9]
Output: "9534330"

Example 3:

1
2
Input: nums = [1]
Output: "1"

Example 4:

1
2
Input: nums = [10]
Output: "10"

Constraints:

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 10^9


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
    struct comp {
        bool operator() (int a, int b) {
            string comb1 = to_string(a) + to_string(b);
            string comb2 = to_string(b) + to_string(a);
            return comb1 > comb2;
        }
    } mycomp;
public:
    string largestNumber(vector<int>& nums) {
        sort(nums.begin(), nums.end(), mycomp);
        if (nums[0] == 0) return "0";
        string res = "";
        for (auto num : nums) {
            res = res + to_string(num);
        }
        return res;
    }
};




Related Posts

String Without Aaa Or Bbb Problem

LeetCode 984. Given two integers a and b, return any...

Shifting Letters Problem

LeetCode 848. You are given a string s of lowercase...

Positions Of Large Groups Problem

LeetCode 830. In a string sof lowercase letters, these letters...

Orderly Queue Problem

LeetCode 899. You are given a string s and an...

Number Of Lines To Write String Problem

LeetCode 806. You are given a string s of lowercase...

Masking Personal Information Problem

LeetCode 831. You are given a personal information string s,...