Interview Question

Software Development Engineer - Search Analytics Interview Palo Alto, CA

Given an array of integers, find the largest possible

  number you can make from all the integers combined.
Answer

Interview Answer

1 Answer

1

public class Solution {

    public String largestNumber(int[] num) {
        if(num == null || num.length == 0){
            return "0";
        }
        StringBuilder sb = new StringBuilder();
        NumberString[] nums = new NumberString[num.length];
        for(int i = 0; i < num.length; i++){
            nums[i] = new NumberString(num[i]);
        }
        Arrays.sort(nums);
        for(NumberString n : nums){
            sb.append(n.str);
        }
        if(sb.toString().charAt(0) == '0'){
            return "0";
        }
        return sb.toString();
    }

    public class NumberString implements Comparable<NumberString> {
        String str;
        public NumberString(int num){
            str = num + "";
        }

        public int compareTo(NumberString other) {
            String str1 = this.str + other.str;
            String str2 = other.str + this.str;
            return str2.compareTo(str1);
        }
    }
}

Kang on May 6, 2015

Add Answers or Comments

To comment on this, Sign In or Sign Up.