1. Largest Number

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

For example, given[3, 30, 34, 5, 9], the largest formed number is9534330.

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

public class Solution {
    public String largestNumber(int[] nums) {

        if(nums.length == 0)  return "0";

        int n = nums.length;
        String[] strs = new String[n];

        for(int i = 0; i < n; i ++)
            strs[i] = String.valueOf(nums[i]);

        Arrays.sort(strs, (s1, s2) -> (s2+s1).compareTo(s1+s2));

        if(strs[0].startsWith("0")) return "0";

        StringBuilder res = new StringBuilder();
        for(String str: strs)
            res.append(str);

        return res.toString();
    }
}

results matching ""

    No results matching ""