Browse Source

valid number

Zhang Li 2 years ago
parent
commit
9780fe1148
2 changed files with 64 additions and 0 deletions
  1. 1 0
      src/solutions/other/mod.rs
  2. 63 0
      src/solutions/other/valid_number.rs

+ 1 - 0
src/solutions/other/mod.rs

@@ -5,3 +5,4 @@ mod merge_intervals;
 mod rotate_image;
 mod spiral_matrix;
 mod spiral_matrix_2;
+mod valid_number;

+ 63 - 0
src/solutions/other/valid_number.rs

@@ -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);
+    }
+}