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

Largest Number Problem

LeetCode 179. Given a list of non-negative integers nums, arrange...

Excel Sheet Column Title Problem

LeetCode 168. Given an integer columnNumber, return its corresponding column...

Excel Sheet Column Number Problem

LeetCode 171. Given a string columnTitle that represents the column...

Valid Number Problem

LeetCode 65. Given a string s, return true if s...

Text Justification Problem

LeetCode 68. Given an array of strings words and a...

Valid Number Problem

LeetCode 67. A robot is located at the top-left corner...