I am new to rust and I am trying to solve this leetcode question, I wrote the following code snippet
fn main() {
println!("{}", Solution::my_pow(0.00001, 2147483647))
}
struct Solution {}
impl Solution {
pub fn my_pow(x: f64, n: i32) -> f64 {
let mut base = x;
let mut exp = n;
let mut res = 1.0;
if n < 0 {
base = 1.0 / base;
exp = -n;
}
let mut i = 1;
while exp != 0 {
let mut temp = base;
while i * 2 <= exp {
temp *= temp;
i *= 2;
}
res *= temp;
exp -= i;
i = 1;
}
res
}
}
when I run the code, it panicked and print an error message say thread 'main' panicked at 'attempt to multiply with overflow', src/main.rs:19:19
, but the following code snippet
impl Solution {
pub fn my_pow(x: f64, n: i32) -> f64 {
fn pow(x: f64, res: f64, n: i64) -> f64 {
match n {
0 => res,
n if n & 1 == 1 => pow(x*x, res*x, n>>1),
_ => pow(x*x, res, n>>1)
}
}
match n {
0 => 1.0,
n if n < 0 => pow(1.0/x, 1.0, (n as i64).abs()),
_ => pow(x, 1.0, n as i64)
}
}
}
could run just as expected. I am confused. What is the difference between the two code snippets?
question from:
https://stackoverflow.com/questions/65872046/what-is-the-difference-between-dirct-multiplication-and-recursion-in-rust 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…