Skip to content

Latest commit

 

History

History
41 lines (32 loc) · 863 Bytes

179.md

File metadata and controls

41 lines (32 loc) · 863 Bytes

排列最大数

题目: https://leetcode.cn/problems/largest-number/

这是一道排序题, 需要自定义排序方式.

class Solution {
public:
    string largestNumber(vector<int> &nums) {
        if (nums.empty()) {
            return {};
        }

        sort(nums.begin(), nums.end(), [](int lhs, int rhs) -> bool {
            int64_t leftBase = 10;
            while (leftBase <= lhs) {
                leftBase *= 10;
            }

            int64_t rightBase = 10;
            while (rightBase <= rhs) {
                rightBase *= 10;
            }

            return lhs * rightBase + rhs > rhs * leftBase + lhs;
        });

        if (nums.front() == 0) {
            return "0";
        }

        string result;
        for (int num: nums) {
            result += to_string(num);
        }

        return result;
    }
};