Share my 8ms C++ solution

• ``````class Solution {
public:
string largestNumber(vector<int> &num) {
string ret = "";
bool f = true;

//check all zero
for_each(num.begin(), num.end(), [&f](int i) {
if(i != 0)
f = false;
});
if(f) return "0";

//sort
sort(num.begin(), num.end(), [this](int l, int r){
int d, p;
int bl = fastcount(l);
int br = fastcount(r);

if(bl == br) return l > r;

int cl = l;
for(int i = 0; i < br; ++i)
cl *= 10;
cl += r;
int cr = r;
for(int i = 0; i < bl; ++i)
cr *= 10;
cr += l;
return cl > cr;
});

//combine
for_each(num.begin(), num.end(), [this, &ret](int i) {
char b[15] = {0};
sprintf(b, "%d", i);
ret += b;
});
return ret;
}

int fastcount(int l) {
if(l < 10) return 1;
else if(l < 100) return 2;
else if(l < 1000) return 3;
else if(l < 10000) return 4;
else if(l < 100000) return 5;
else if(l < 1000000) return 6;
else if(l < 10000000) return 7;
else if(l < 100000000) return 8;
else return fastcount(l / 10) + 1;
}
};``````

• What's the intuition behind:
int cl = l;
for(int i = 0; i < br; ++i)
cl *= 10;
cl += r;
int cr = r;
for(int i = 0; i < bl; ++i)
cr *= 10;
cr += l;
return cl > cr;

How does that produce a viable comparison?

• Glad that you used the lambda function

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