[英]How can I convert u32 datatype to bigInt in Rust?
I am doing Fibonacci sequence function and the return type should return BigUint type.我正在做斐波那契数列 function 并且返回类型应该返回 BigUint 类型。 I search through many webs but I couldn't find the site that show the way.我搜索了很多网站,但找不到显示方式的网站。 This is my process so far.到目前为止,这是我的过程。
pub fn fibo_seq(n: u32) -> Vec<num_bigint::BigUint> {
let mut f1 = 0;
let mut temp = 1;
let mut f2 = 1;
let mut vec:Vec<u32> = Vec::new();
while vec.len() < n.try_into().unwrap(){
vec.push(f2);
temp = f2;
f2 = f1 + f2;
f1 = temp;
}
vec // return wrong data type
}
You can't just put BigUint
in the return type, you have to actually use it!您不能只将BigUint
放在返回类型中,您必须实际使用它!
pub fn fibo_seq(n: u32) -> Vec<BigUint> {
let mut f1 = BigUint::from(0u32);
let mut temp = BigUint::from(1u32);
let mut f2 = BigUint::from(1u32);
let mut vec: Vec<BigUint> = Vec::new();
while vec.len() < n.try_into().unwrap(){
vec.push(f2.clone());
temp = f2.clone();
f2 = f1 + &f2;
f1 = temp;
}
vec
}
Since you are return Vec<BigUint>
you need Vec<BigUint>
instead of Vec<u32>
.由于您要返回Vec<BigUint>
,因此您需要Vec<BigUint>
而不是 Vec<u32 Vec<u32>
。
To improve you can rewrite the same method without temp variable as below.要改进,您可以重写相同的方法而不使用临时变量,如下所示。
use num_bigint::BigUint;
pub fn fibo_seq(n: u32) -> Vec<BigUint> {
let mut f1 = BigUint::from(0u32);
let mut f2 = BigUint::from(1u32);
let mut vec:Vec<BigUint> = Vec::new();
while vec.len() < n.try_into().unwrap() {
(f2, f1) = (f1 + &f2, f2);
vec.push(f1.clone());
}
vec
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.