1
Fork 0

Solve valid-number.

This commit is contained in:
Bauke 2022-04-14 13:36:13 +02:00
parent 9512a94b6d
commit 23f5b6b769
Signed by: Bauke
GPG Key ID: C1C0F29952BCF558
3 changed files with 37 additions and 0 deletions

View File

@ -18,6 +18,7 @@ pub mod roman_to_integer;
pub mod set_mismatch; pub mod set_mismatch;
pub mod two_sum; pub mod two_sum;
pub mod valid_anagram; pub mod valid_anagram;
pub mod valid_number;
pub mod valid_palindrome; pub mod valid_palindrome;
pub mod valid_parenthesis; pub mod valid_parenthesis;
pub mod word_pattern; pub mod word_pattern;

View File

@ -0,0 +1,23 @@
pub fn is_number(string: String) -> bool {
let string = string.to_lowercase();
if string.contains("inf") || string.contains("nan") {
return false;
}
let mut parts = string.split("e");
let valid_significand = match parts.next() {
Some(part) => part.parse::<f64>().is_ok(),
None => unreachable!(),
};
let valid_exponent = match parts.next() {
Some(part) => part.parse::<isize>().is_ok(),
None => true,
};
let nothing_remaining = parts.next().is_none();
valid_significand && valid_exponent && nothing_remaining
}

13
tests/valid_number.rs Normal file
View File

@ -0,0 +1,13 @@
use leetcode::valid_number::is_number;
use test_case::test_case;
#[test_case("0", true; "example 1")]
#[test_case("e", false; "example 2")]
#[test_case(".", false; "example 3")]
#[test_case("-inf", false; "infinity")]
#[test_case("NaN", false; "not a number")]
#[test_case("", false; "empty")]
fn test_valid_number(input: &str, expected: bool) {
assert_eq!(is_number(input.to_string()), expected);
}