|
@@ -0,0 +1,63 @@
|
|
|
+struct Solution;
|
|
|
+
|
|
|
+impl Solution {
|
|
|
+ pub fn is_number(s: String) -> bool {
|
|
|
+ if let Some(e) = s.chars().position(|c| c == 'e' || c == 'E') {
|
|
|
+ Self::is_decimal(&s[0..e]) && Self::is_integer(&s[e + 1..])
|
|
|
+ } else {
|
|
|
+ Self::is_decimal(&s[..])
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ fn is_integer(s: &str) -> bool {
|
|
|
+ let mut ans = false;
|
|
|
+ for (i, c) in s.chars().enumerate() {
|
|
|
+ match c {
|
|
|
+ '+' | '-' if i == 0 => {}
|
|
|
+ '0'..='9' => ans = true,
|
|
|
+ _ => return false,
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ ans
|
|
|
+ }
|
|
|
+
|
|
|
+ fn is_decimal(s: &str) -> bool {
|
|
|
+ let mut num = false;
|
|
|
+ let mut dot = false;
|
|
|
+
|
|
|
+ for (i, c) in s.chars().enumerate() {
|
|
|
+ match c {
|
|
|
+ '0'..='9' => num = true,
|
|
|
+ '+' | '-' if i == 0 => {}
|
|
|
+ '.' if !dot => dot = true,
|
|
|
+ _ => return false,
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ num
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+#[cfg(test)]
|
|
|
+mod tests {
|
|
|
+ use super::*;
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ fn test_case_1() {
|
|
|
+ let s = "0";
|
|
|
+ assert_eq!(Solution::is_number(s.to_string()), true);
|
|
|
+ }
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ fn test_case_2() {
|
|
|
+ let s = "e";
|
|
|
+ assert_eq!(Solution::is_number(s.to_string()), false);
|
|
|
+ }
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ fn test_case_3() {
|
|
|
+ let s = ".";
|
|
|
+ assert_eq!(Solution::is_number(s.to_string()), false);
|
|
|
+ }
|
|
|
+}
|