[ LeetCode #179] Largest Number

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 is 9534330.
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[] num) {

		String[] NUM = new String[num.length];

		for (int i = 0; i < num.length; i++) {
			NUM[i] = String.valueOf(num[i]);
		}

		java.util.Arrays.sort(NUM, new java.util.Comparator<String>() {
			public int compare(String left, String right) {
				String leftRight = left.concat(right);
				String rightLeft = right.concat(left);
				return rightLeft.compareTo(leftRight);
			}
		});

		java.lang.StringBuffer buffer = new java.lang.StringBuffer();
		for (int i = 0; i < NUM.length; i++) {
			buffer.append(NUM[i]);
		}
		// String result = buffer.toString();
		java.math.BigInteger result = new java.math.BigInteger(
				buffer.toString());
		return result.toString();
	}

	public static void main(String args[]) {
		Solution s = new Solution();
		{
			int A[] = new int[] { 0, 0 };
			String solution = s.largestNumber(A);
			System.out.println("Solution : " + solution);
		}
		{
			int A[] = new int[] { 128, 12, 320, 32 };
			String solution = s.largestNumber(A);
			System.out.println("Solution : " + solution);
		}

		{
			int A[] = new int[] { 3, 30, 34, 5, 9 };
			String solution = s.largestNumber(A);
			System.out.println("Solution : " + solution);
		}

	}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s