我是 rust 病新手,正在尝试解决this leetcode问题,我写了以下代码段
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
}
}
当我运行代码时,它 panic 并打印一条错误消息,说thread 'main' panicked at 'attempt to multiply with overflow', src/main.rs:19:19
,但以下代码段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)
}
}
}
可以按预期运行。我很迷惑。这两个代码段之间有什么区别?
最佳答案
What is the difference between the two code snippets?
其中一个溢出,而另一个不溢出。您是否考虑过阅读错误消息,并想知道这与您的代码有什么关系? panic 指向:
while i * 2 <= exp {
您没有指定i
的类型就定义了它,这意味着它是i32
(32b有符号整数,二进制补码)。您一直将其乘以2,因此除了其初始值之外,它只能是偶数,并且一直这样做,直到它大于exp
为止,后者最初是n
,也就是2147483647
。大于
2147483647
的偶数是2147483648
,它不是有效的i32,因此会溢出。 panic 告诉你的是什么。
关于rust - rust 的直接乘法和递归之间有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65872046/