a528. 大數排序 5/16/2025

解法一、函式庫

用 sort() 排序

題目數字超出 long long 範圍
因此使用字串,然後自訂比較函式 comp(string& a, string& b)

✅ 完整代碼

評分結果(參考) : AC (3ms, 376KB)

#include <bits/stdc++.h>
using namespace std;

// a > b
bool comp(string& a, string& b){
    bool negA = (a[0] == '-');
    bool negB = (b[0] == '-');
    
    if(negA && !negB) return true;
    if(!negA && negB) return false;
    
    if(a.size() > b.size()) return negA;
    if(a.size() < b.size()) return !negA;
    
    for(int i=0; i<a.size(); i++){
        if(a[i] == '-') continue;

        if(a[i] > b[i]) return negA;
        else if(a[i] < b[i]) return !negA;
    }
    
    return false;
}

int main(){    
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    while(cin >> n){
        vector<string> nums(n);
        for(string& s : nums) cin >> s;

        sort(nums.begin(), nums.end(), comp);
        for(string& s : nums) cout << s << "\n";
    }
    
    return 0;
}