Largest Number

Himanshu DubeyHimanshu Dubey
2 min read

Hello DSA enthusiasts, I'm here a long time back.

Let's directly jump to today's motive of the article. We will be solving a Leetcode problem today, Largest Number(179)

First, I'm inserting the link to the same, https://leetcode.com/problems/largest-number/description/

If you've seen the problem and tried your approach, it is great. Otherwise, let's dive deep into the approach.

As the problem says, we have to return the largest number from the list of numbers given. The direct inference is, we need to sort the numbers and concatenate them. Don't forget we have to take them in form string first.

We will be using compare function while sorting. The description of the same is given as let

nums = [3, 34, 30], here we will be using to_string function in compare class. to_string() method takes a single integer variable or other data type and converts it into a string. To choose the numbers, we need to have first we will return this,

bool compare(int a, int b){
return to_string(a), to_string(b)
}

So, the output looks like

nums = [34, 3, 30]

Now, we will concatenate this into a string and return it.

Full code in C++ is given below, you may change it in your favourite programming language.

bool compare(int a, int b){
   return to_string(a) + to_string(b);
}
class Solution {
public:
    string largestNumber(vector<int>& nums) {
        sort(nums.begin(), nums.end(), compare);
        string ans = "";
        for(int i=0; i<nums.size();i++){
            ans+=to_string(nums[i]);
        }
        if(ans[0]=='0') return "0";
        return ans;
    }
};

Hope you liked the approach and can solve the problem with full confidence now.

If you've any sort of doubt related to this problem, you may comment below.

Take care :)

0
Subscribe to my newsletter

Read articles from Himanshu Dubey directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Himanshu Dubey
Himanshu Dubey

Exploring Tech