1. 程式人生 > >#Leetcode# 179. Largest Number

#Leetcode# 179. Largest Number

https://leetcode.com/problems/largest-number/

 

Given a list of non negative integers, arrange them such that they form the largest number.

Example 1:

Input: [10,2]
Output: "210"

Example 2:

Input: [3,30,34,5,9]
Output: "9534330"

未提交程式碼:

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

int n;
int num[1010];

struct Node {
    char s[40];
}node[1010];

int bigger(const Node& a, const Node& b) {
    int la = strlen(a.s), lb = strlen(b.s);
    int minn = min(la, lb);
    for(int i = 0; i < minn; i ++) {
        if(a.s[i] == b.s[i]) continue;
        else if(a.s[i] > b.s[i]) return 1;
        else return -1;
    }
    if(minn == la && b.s[minn] > a.s[0]) return -1;
    else if(minn == la && b.s[minn] < a.s[0]) return 1;
    else if(minn = lb && a.s[minn] > b.s[0]) return 1;
    return -1;
}

bool cmp(const Node& a, const Node& b) {
    return bigger(a, b) > 0;
}

int main() {
    scanf("%d", &n);
    int cnt;
    for(int i = 0; i < n; i ++) {
        cnt = 0;
        scanf("%d", &num[i]);
        while(num[i]) {
            node[i].s[cnt ++] = (num[i] % 10 + '0');
            num[i] /= 10;
        }
        for(int j = 0; j < cnt / 2; j ++)
            swap(node[i].s[j], node[i].s[cnt - j - 1]);
    }

    sort(node, node + n, cmp);
    for(int i = 0; i < n; i ++)
        printf("%s", node[i].s);
    return 0;
}

  啊啊啊 又一次被格式限制的我 等著 FH 下班搞了