Zhang Li 2 years ago
parent
commit
e3df0c679b
2 changed files with 49 additions and 0 deletions
  1. 1 0
      src/solutions/recrusion/mod.rs
  2. 48 0
      src/solutions/recrusion/pow.rs

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

@@ -1 +1,2 @@
 mod next_permutation;
+mod pow;

+ 48 - 0
src/solutions/recrusion/pow.rs

@@ -0,0 +1,48 @@
+struct Solution;
+
+impl Solution {
+    pub fn my_pow(x: f64, n: i32) -> f64 {
+        let coe = if n > 0 { 1 } else { -1 };
+
+        if x == 0. {
+            return 0.;
+        }
+        if n == 0 {
+            return 1.;
+        }
+        if n == 1 {
+            return x;
+        }
+        let n = (n as i64).abs();
+        let res = if n % 2 == 0 {
+            Self::my_pow(x * x, (n / 2) as i32)
+        } else {
+            x * Self::my_pow(x * x, ((n - 1) / 2) as i32)
+        };
+
+        if coe == 1 {
+            res
+        } else {
+            1. / res
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    #[test]
+    fn test_my_pow() {
+        assert_eq!(Solution::my_pow(2.0, 10), 1024.0);
+    }
+
+    #[test]
+    fn test_my_pow_1() {
+        assert_eq!(Solution::my_pow(-2.0, -3), -0.125);
+    }
+
+    #[test]
+    fn test_my_pow_2() {
+        assert_eq!(Solution::my_pow(2.0, 0), 1.0);
+    }
+}