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