My java pass code


  • 0
    S

    The idea to append two string together and define which combination is larger one. Be careful with test case {0,0}.

    public String largestNumber(int[] num) {
                if (num == null || num.length == 0) {
                    return "";
                }
                
                String []convert = new String[num.length];
                for (int i = 0; i < num.length; i++) {
                    convert[i] = String.valueOf(num[i]);
                }
                
                Arrays.sort(convert, new MyComparator());
                StringBuilder sb = new StringBuilder();
                for (int i = convert.length - 1; i >= 0; i--) {
                	sb.append(convert[i]);
                }
                int start = 0;
                while (start < sb.length() && sb.charAt(start) == '0') {
                    start++;
                }
                
                if (start == sb.length()) {
                	return "0";
                } 
                
                return sb.toString();
            }
            
            class MyComparator implements Comparator<String> {
        		@Override
        		public int compare(String o1, String o2) {
        			// TODO Auto-generated method stub
        			String tmp1 = o1 + o2;
        			String tmp2 = o2 + o1;
        			return tmp1.compareTo( tmp2);
        		}
            }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.