|
| 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