Ad
Numbers
Data Types
Integers
Algorithms
Logic
Code
Diff
  • fn digits(n: u64, base: u64) -> usize {
        DigitIterator::new(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 }
        }
    }
    
    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)
                }
            }
        }
    }
    • fn digits(n: u64, base: u64) -> usize {
    • DigitIterator::new(n, base).count()
    • }
    • struct DigitIterator{
    • value: u64,
    • base: u64,
    • is_0: bool,
    • first_iter: bool
    • enum DigitIterator {
    • RemainingDigits { value: u64, base: u64 },
    • Done,
    • }
    • impl DigitIterator{
    • pub fn new(value: u64, base: u64) -> Self{
    • Self{
    • value,
    • base,
    • is_0: value == 0,
    • first_iter: true,
    • }
    • impl DigitIterator {
    • pub fn new(value: u64, base: u64) -> Self {
    • Self::RemainingDigits { value, base }
    • }
    • }
    • impl Iterator for DigitIterator{
    • impl Iterator for DigitIterator {
    • type Item = u64;
    • fn next(&mut self) -> Option<u64>{
    • if self.is_0 {
    • if self.first_iter{
    • self.first_iter = false;
    • Some(0)
    • }else{
    • None
    • }
    • }else{
    • let old = self.value;
    • self.value /= self.base;
    • if old != 0{
    • Some(old % self.base)
    • }else{
    • None
    • use DigitIterator::*;
    • match self {
    • Done => None,
    • RemainingDigits { value, base } => {
    • let digit = *value % *base;
    • *value /= *base;
    • if *value == 0 { *self = Done; }
    • Some(digit)
    • }
    • }
    • }
    • }