From 5cc6a24e38f922a60e51baf26ccb2909fc29312e Mon Sep 17 00:00:00 2001 From: nkawaller Date: Tue, 23 Jan 2024 06:36:33 -0500 Subject: [PATCH] Pow(x, n) solution --- rust/0050-powx-n.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 rust/0050-powx-n.rs diff --git a/rust/0050-powx-n.rs b/rust/0050-powx-n.rs new file mode 100644 index 000000000..56d34eaa6 --- /dev/null +++ b/rust/0050-powx-n.rs @@ -0,0 +1,26 @@ +impl Solution { + pub fn my_pow(x: f64, n: i32) -> f64 { + fn helper(x: f64, n: i32) -> f64 { + match (x, n) { + (0.0, _) => 0.0, + (_, 0) => 1.0, + _ => { + let res = helper(x * x, n / 2); + if n % 2 == 0 { + res + } else { + x * res + } + } + } + } + + let res = helper(x, n.abs()); + + if n >= 0 { + res + } else { + 1.0 / res + } + } +}