Skip to content

Commit d8cd55a

Browse files
committed
1903. Largest Odd Number in String: AC
1 parent 5e41888 commit d8cd55a

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed

src/solution/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1434,3 +1434,4 @@ mod s1898_maximum_number_of_removable_characters;
14341434
mod s1899_merge_triplets_to_form_target_triplet;
14351435
mod s1900_the_earliest_and_latest_rounds_where_players_compete;
14361436
mod s1901_find_a_peak_element_ii;
1437+
mod s1903_largest_odd_number_in_string;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
/**
2+
* [1903] Largest Odd Number in String
3+
*
4+
* You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string "" if no odd integer exists.
5+
* A substring is a contiguous sequence of characters within a string.
6+
*
7+
* Example 1:
8+
*
9+
* Input: num = "52"
10+
* Output: "5"
11+
* Explanation: The only non-empty substrings are "5", "2", and "52". "5" is the only odd number.
12+
*
13+
* Example 2:
14+
*
15+
* Input: num = "4206"
16+
* Output: ""
17+
* Explanation: There are no odd numbers in "4206".
18+
*
19+
* Example 3:
20+
*
21+
* Input: num = "35427"
22+
* Output: "35427"
23+
* Explanation: "35427" is already an odd number.
24+
*
25+
*
26+
* Constraints:
27+
*
28+
* 1 <= num.length <= 10^5
29+
* num only consists of digits and does not contain any leading zeros.
30+
*
31+
*/
32+
pub struct Solution {}
33+
34+
// problem: https://leetcode.com/problems/largest-odd-number-in-string/
35+
// discuss: https://leetcode.com/problems/largest-odd-number-in-string/discuss/?currentPage=1&orderBy=most_votes&query=
36+
37+
// submission codes start here
38+
39+
impl Solution {
40+
pub fn largest_odd_number(num: String) -> String {
41+
num.as_bytes()
42+
.iter()
43+
.rposition(|&b| b & 1 == 1)
44+
.map_or(String::new(), |p| num[..=p].to_string())
45+
}
46+
}
47+
48+
// submission codes end
49+
50+
#[cfg(test)]
51+
mod tests {
52+
use super::*;
53+
54+
#[test]
55+
fn test_1903_example_1() {
56+
let num = "52".to_string();
57+
58+
let result = "5".to_string();
59+
60+
assert_eq!(Solution::largest_odd_number(num), result);
61+
}
62+
63+
#[test]
64+
fn test_1903_example_2() {
65+
let num = "4206".to_string();
66+
67+
let result = "".to_string();
68+
69+
assert_eq!(Solution::largest_odd_number(num), result);
70+
}
71+
72+
#[test]
73+
fn test_1903_example_3() {
74+
let num = "35427".to_string();
75+
76+
let result = "35427".to_string();
77+
78+
assert_eq!(Solution::largest_odd_number(num), result);
79+
}
80+
}

0 commit comments

Comments
 (0)