Create an algorithm that arranges them in order to form the largest possible integer

By | July 2, 2023

Given a list of numbers, create an algorithm that arranges them in order to form the largest possible integer. For example, given [10, 7, 76, 415], you should return 77641510.

Javascript

function largestNumber(nums) {
  nums.sort((a, b) => {
    const order1 = String(a) + String(b);
    const order2 = String(b) + String(a);
    return order2.localeCompare(order1);
  });
  return nums.join('');
}
// Example usage
const numbers = [10, 7, 76, 415];
const result = largestNumber(numbers);
console.log(result);

Java 

import java.util.Arrays;
import java.util.Comparator;
public class LargestNumber {
    public static String largestNumber(int[] nums) {
        String[] numStrings = new String[nums.length];
        for (int i = 0; i < nums.length; i++) {
            numStrings[i] = String.valueOf(nums[i]);
        }
        Arrays.sort(numStrings, new Comparator<String>() {
            public int compare(String a, String b) {
                String order1 = a + b;
                String order2 = b + a;
                return order2.compareTo(order1);
            }
        });
        if (numStrings[0].equals("0")) {
            return "0"; // If the largest number is 0, return "0"
        }
        StringBuilder result = new StringBuilder();
        for (String numString : numStrings) {
            result.append(numString);
        }
        return result.toString();
    }
    public static void main(String[] args) {
        int[] numbers = {10, 7, 76, 415};
        String result = largestNumber(numbers);
        System.out.println(result);
    }
}

Python:

def largest_number(nums):
    nums.sort(key=lambda x: str(x), reverse=True)
    largest_int = ''.join(map(str, nums))
    return largest_int
# Example usage
numbers = [10, 7, 76, 415]
result = largest_number(numbers)
print(result)

Leave a Reply

Your email address will not be published. Required fields are marked *