Hi, I am wondering, is there any way of iterating over digits of a number in a straight order?
I mean significant figures of course.
The example will be:
123 -> iterate over [1, 2, 3]
I am trying to find a solution without using conversion to a String, basically without any memory allocation..
The only way I can think of is to first reverse a number and then go through the digits of the reversed number, would love to hear more ideas.
fn digits(mut x: u32) -> impl Iterator<Item = u32> {
let iter = std::iter::from_fn(move || {
if x > 0 {
let digit = x % 10;
x /= 10;
Some(digit)
} else {
None
}
});
(x == 0).then_some(0).into_iter().chain(iter)
}
And generically:
fn digits<T>(mut x: T) -> impl Iterator<Item = T>
where
T: From<u8> + Copy + PartialOrd + DivAssign + Rem<Output = T>
{
let zero = T::from(0);
let ten = T::from(10);
let iter = std::iter::from_fn(move || {
if x > zero {
let digit = x % ten;
x /= ten;
Some(digit)
} else {
None
}
});
(x == zero).then_some(zero).into_iter().chain(iter)
}