forked from Mohammed-Shoaib/Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC0179.cpp
More file actions
executable file
·42 lines (39 loc) · 759 Bytes
/
LC0179.cpp
File metadata and controls
executable file
·42 lines (39 loc) · 759 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
Problem Statement: https://leetcode.com/problems/largest-number/
Time: O(n • log n)
Space: O(n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
private:
static int64_t convert(vector<int> nums) {
int64_t num = 0;
for (int x: nums) {
int copy = x;
while (copy) {
num *= 10;
copy /= 10;
}
num += x;
}
return num;
}
static bool compare(int l, int r) {
int64_t lr, rl;
if (l == 0 || r == 0)
return l > r;
lr = convert({l, r});
rl = convert({r, l});
return lr > rl;
}
public:
string largestNumber(vector<int>& nums) {
string s;
sort(nums.begin(), nums.end(), compare);
if (!nums.empty() && nums[0] == 0)
return "0";
for (int& x: nums)
s += to_string(x);
return s;
}
};