Given a list of non-negative integers nums
, arrange them such that they form the largest number.
Note: The result may be very large, so you need to return a string instead of an integer.
Example 1:
Input: nums = [10,2] Output: "210"
Example 2:
Input: nums = [3,30,34,5,9] Output: "9534330"
Example 3:
Input: nums = [1] Output: "1"
Example 4:
Input: nums = [10] Output: "10"
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 109
struct Solution;
impl Solution {
fn largest_number(nums: Vec<i32>) -> String {
let mut v: Vec<String> = nums.iter().map(|x| x.to_string()).collect();
v.sort_unstable_by(|a, b| format!("{}{}", b, a).cmp(&format!("{}{}", a, b)));
let mut res: String = "".to_string();
if v[0] == "0" {
return "0".to_string();
}
for s in v {
res += &s;
}
res
}
}
#[test]
fn test() {
let nums = vec![10, 2];
let res = "210".to_string();
assert_eq!(Solution::largest_number(nums), res);
let nums = vec![3, 30, 34, 5, 9];
let res = "9534330".to_string();
assert_eq!(Solution::largest_number(nums), res);
let nums = vec![0, 0];
let res = "0".to_string();
assert_eq!(Solution::largest_number(nums), res);
let nums = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let res = "9876543210".to_string();
assert_eq!(Solution::largest_number(nums), res);
}