From 41d30f4a75bb1429bbfb6f6645a918c178898e36 Mon Sep 17 00:00:00 2001 From: Michael Xu Date: Mon, 24 Jul 2023 23:12:14 +0800 Subject: [PATCH] feat: add rust solution to lc problem: No.0050 --- solution/0000-0099/0050.Pow(x, n)/README.md | 31 +++++++++++++++++++ .../0000-0099/0050.Pow(x, n)/README_EN.md | 31 +++++++++++++++++++ solution/0000-0099/0050.Pow(x, n)/Solution.rs | 26 ++++++++++++++++ 3 files changed, 88 insertions(+) create mode 100644 solution/0000-0099/0050.Pow(x, n)/Solution.rs diff --git a/solution/0000-0099/0050.Pow(x, n)/README.md b/solution/0000-0099/0050.Pow(x, n)/README.md index 260f824967882..36940e8b5603a 100644 --- a/solution/0000-0099/0050.Pow(x, n)/README.md +++ b/solution/0000-0099/0050.Pow(x, n)/README.md @@ -124,6 +124,37 @@ public: }; ``` +### **Rust** + +```rust +impl Solution { + #[allow(dead_code)] + pub fn my_pow(x: f64, n: i32) -> f64 { + let mut x = x; + let n = n as i64; + if n >= 0 { + Self::quick_pow(&mut x, n) + } else { + 1.0 / Self::quick_pow(&mut x, -n) + } + } + + #[allow(dead_code)] + fn quick_pow(x: &mut f64, mut n: i64) -> f64 { + // `n` should greater or equal to zero + let mut ret = 1.0; + while n != 0 { + if n & 0x1 == 1 { + ret *= *x; + } + *x *= *x; + n >>= 1; + } + ret + } +} +``` + ### **Go** ```go diff --git a/solution/0000-0099/0050.Pow(x, n)/README_EN.md b/solution/0000-0099/0050.Pow(x, n)/README_EN.md index 35af56e6c70c9..6f2a5d053b50d 100644 --- a/solution/0000-0099/0050.Pow(x, n)/README_EN.md +++ b/solution/0000-0099/0050.Pow(x, n)/README_EN.md @@ -108,6 +108,37 @@ public: }; ``` +### **Rust** + +```rust +impl Solution { + #[allow(dead_code)] + pub fn my_pow(x: f64, n: i32) -> f64 { + let mut x = x; + let n = n as i64; + if n >= 0 { + Self::quick_pow(&mut x, n) + } else { + 1.0 / Self::quick_pow(&mut x, -n) + } + } + + #[allow(dead_code)] + fn quick_pow(x: &mut f64, mut n: i64) -> f64 { + // `n` should greater or equal to zero + let mut ret = 1.0; + while n != 0 { + if n & 0x1 == 1 { + ret *= *x; + } + *x *= *x; + n >>= 1; + } + ret + } +} +``` + ### **Go** ```go diff --git a/solution/0000-0099/0050.Pow(x, n)/Solution.rs b/solution/0000-0099/0050.Pow(x, n)/Solution.rs new file mode 100644 index 0000000000000..95eb1fbc897bc --- /dev/null +++ b/solution/0000-0099/0050.Pow(x, n)/Solution.rs @@ -0,0 +1,26 @@ +impl Solution { + #[allow(dead_code)] + pub fn my_pow(x: f64, n: i32) -> f64 { + let mut x = x; + let n = n as i64; + if n >= 0 { + Self::quick_pow(&mut x, n) + } else { + 1.0 / Self::quick_pow(&mut x, -n) + } + } + + #[allow(dead_code)] + fn quick_pow(x: &mut f64, mut n: i64) -> f64 { + // `n` should greater or equal to zero + let mut ret = 1.0; + while n != 0 { + if n & 0x1 == 1 { + ret *= *x; + } + *x *= *x; + n >>= 1; + } + ret + } +} \ No newline at end of file