Skip to content

Commit 0ba09bd

Browse files
committed
solve #179
1 parent f9d6097 commit 0ba09bd

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -161,3 +161,4 @@ mod n0171_excel_sheet_column_number;
161161
mod n0172_factorial_trailing_zeroes;
162162
mod n0173_binary_search_tree_iterator;
163163
mod n0174_dungeon_game;
164+
mod n0179_largest_number;

src/n0179_largest_number.rs

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* [179] Largest Number
3+
*
4+
* Given a list of non negative integers, arrange them such that they form the largest number.
5+
*
6+
* Example 1:
7+
*
8+
*
9+
* Input: [10,2]
10+
* Output: "210"
11+
*
12+
* Example 2:
13+
*
14+
*
15+
* Input: [3,30,34,5,9]
16+
* Output: "9534330"
17+
*
18+
*
19+
* Note: The result may be very large, so you need to return a string instead of an integer.
20+
*
21+
*/
22+
pub struct Solution {}
23+
24+
// submission codes start here
25+
26+
impl Solution {
27+
pub fn largest_number(nums: Vec<i32>) -> String {
28+
let mut nums = nums.into_iter().map(|num| {num.to_string()}).collect::<Vec<_>>();
29+
nums.sort_unstable_by(|a, b| {
30+
format!("{}{}", b, a).cmp(&format!("{}{}", a, b))
31+
});
32+
if nums[0] == "0" { return "0".to_owned() }
33+
nums.iter().fold(String::new(), |mut s, num| {
34+
s.push_str(num); s
35+
})
36+
}
37+
}
38+
39+
// submission codes end
40+
41+
#[cfg(test)]
42+
mod tests {
43+
use super::*;
44+
45+
#[test]
46+
fn test_179() {
47+
assert_eq!(Solution::largest_number(vec![3,30,34,5,9]), "9534330".to_owned());
48+
assert_eq!(Solution::largest_number(vec![121,12]), "12121".to_owned());
49+
}
50+
}

0 commit comments

Comments
 (0)