179. Largest Number

import java.lang.StringBuilder

/**
 * 179. Largest Number
 * https://leetcode.com/problems/largest-number/description/
 * https://www.cnblogs.com/grandyang/p/4225047.html
 *
 * 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"

Note: The result may be very large, so you need to return a string instead of an integer.
 * */
class Solution {
    fun largestNumber(nums: IntArray): String {
        val nums_ = nums.sortedWith(Comparator { a, b ->
            val aString = a.toString()
            val bString = b.toString()
            when {
                (aString + bString) < (bString + aString) -> 1
                (aString + bString) > (bString + aString) -> -1
                else -> 0
            }
        })
        val result = StringBuilder()
        for (i in 0 until nums_.size) {
            if (nums_.get(0)==0){
                return "0"
            } else {
                result.append(nums_.get(i))
            }
        }
        //print(result.toString())
        return result.toString()
    }
}

 

posted @ 2019-10-01 01:46  johnny_zhao  阅读(148)  评论(0编辑  收藏  举报