Ad
Numbers
Data Types
Integers
Algorithms
Logic
Code
Diff
  • fn digits(n: u64, base: u64) -> usize {
        digits_iter(n, base).count()
    }
    
    fn digits_iter(n: u64, base: u64) -> impl Iterator<Item = u64> {
        let mut n = Some(n);
        std::iter::from_fn(move || match n {
            Some(x) => {
                let digit = x % base;
                n = Some(x / base);
    
                if let Some(0) = n {
                    n = None;
                }
                Some(digit)
            }
            _ => None,
        })
    }
    
    • fn digits(n: u64, base: u64) -> usize {
    • DigitIterator::new(n, base).count()
    • digits_iter(n, base).count()
    • }
    • enum DigitIterator {
    • RemainingDigits { value: u64, base: u64 },
    • Done,
    • }
    • impl DigitIterator {
    • pub fn new(value: u64, base: u64) -> Self {
    • Self::RemainingDigits { value, base }
    • }
    • }
    • fn digits_iter(n: u64, base: u64) -> impl Iterator<Item = u64> {
    • let mut n = Some(n);
    • std::iter::from_fn(move || match n {
    • Some(x) => {
    • let digit = x % base;
    • n = Some(x / base);
    • impl Iterator for DigitIterator {
    • type Item = u64;
    • fn next(&mut self) -> Option<u64>{
    • use DigitIterator::*;
    • match self {
    • Done => None,
    • RemainingDigits { value, base } => {
    • let digit = *value % *base;
    • *value /= *base;
    • if *value == 0 { *self = Done; }
    • Some(digit)
    • if let Some(0) = n {
    • n = None;
    • }
    • Some(digit)
    • }
    • }
    • }
    • _ => None,
    • })
    • }