Skip to content

Largest Number

Problem Description

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

Note: The result may be very large, so you need to return a string instead of an integer.

Problem Constraints

1 <= |A| <= 10^5
0 <= Ai <= 10^9

Input Format

The first argument is an integer array A.

Output Format

Return a string representing the largest number formed

Example Input

A = [3, 30, 34, 5, 9]

Example Output

9534330

Example Explanation

Largest possible number that can be formed is 9534330

Solution

swift
import Foundation

class Solution {
	func largestNumber(_ A: [Int]) -> String {
        var B = A.map{Array(String($0))}
        B.sort{  
            let lr = $0 + $1
            let rl = $1 + $0
            for i in 0..<lr.count{
                let l = lr[i]
                let r = rl[i]
                if l < r {
                    return false
                } else if l > r {
                    return true
                }
            }
            return true   
        }
        var C = B.filter{ $0.count > 1 || $0[0] != "0"}
        if C.count == 0 {
            return "0"
        }
        let ret = C.reduce("",+)
        return ret
	}
}

References