3-line C++ Extremely concise code.

  • 8

    If you write C++, you can utilize STL to simplify your code.
    The code below shows why STL is great to write concise code, though the run time wasn't great because I chose to use string comparison which is expensive (not STL's fault).

    class Solution {
        string largestNumber(vector<int>& nums) {
           sort(nums.begin(), nums.end(), [](int a, int b){ return to_string(a) + to_string(b) > to_string(b) + to_string(a);});
           string result = accumulate(nums.begin(), nums.end(), string(), [](string &r, int a){return r + to_string(a);});
           return result[0] == '0' ? "0" : result;

  • 0

    very concise code, thanks.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.