生锈中访问BigUint的各个数字

时间:2014-09-16 13:13:46

标签: rust

我只是学习生锈,因此这个问题可能有些微不足道的答案。

我想访问生锈BigUint的个别数字。这是一个项目欧拉拼图询问这些数字的总和。

我是这样做的:

let mut f = func(100);
let mut total: BigUint = Zero::zero();
while f > FromPrimitive::from_uint(0).unwrap() {
    let digit = f % FromPrimitive::from_uint(10).unwrap();
    f = f / FromPrimitive::from_uint(10).unwrap();
    total = total + digit;
}
println!("");
println!("Sum of digits of func(100) = {}", total);

它有效,但它非常令人沮丧,因为我相信这些数字是作为数组内部存储的,但我无法直接访问它们,因为基础数据成员是私有的。

有没有办法以更简单的方式做到这一点?

2 个答案:

答案 0 :(得分:1)

BigUint的内部存储空间是BigDigit的向量,它是u32的别名,因此它可能无法帮助您获得基数10的总和位数。

我怀疑转换为String是计算此问题的有效方法,但您可以使用特征div_rem()中的Integer方法使其更直接。 (毕竟,转换为String会在内部进行此计算。)

extern crate num;

use std::num::Zero;
use num::bigint::BigUint;
use num::integer::Integer;

fn main() {
    let mut f = func(100);
    let mut total: BigUint = Zero::zero();
    let ten: BigUint = FromPrimitive::from_uint(10).unwrap();
    while f > Zero::zero() {
        let (quotient, remainder) = f.div_rem(&ten);
        f = quotient;
        total = total + remainder;
    }
    println!("");
    println!("Sum of digits of func(100) = {}", total);
}

答案 1 :(得分:0)

我按照@ C.Quilley的建议使用to_string()结束了。但正如@Levans指出的那样,内部实现只执行div_rem。我仍然喜欢这个版本,因为我认为它更具可读性和直观性。

extern crate num;
use num::bigint::BigUint;

// What this function does is irrelevant
fn func(n: uint) -> BigUint {
    let p : BigUint = FromPrimitive::from_uint(n).unwrap();
    p*p*p*p*p*p*p*p*p*p*p*p*p
}

fn main() {
    let n = 2014u;
    let f = func(n);
    let total: uint = f.to_string().as_slice().chars()
         .fold(0, |a, b| a + b as uint - '0' as uint);
    println!("Sum of digits of func({}) = {} : {}", n, f, total);
}