Digits iteration

Is there an iterator over the digits of a number or should i invent it myself and probably publish?

P.S. Please do not try to explain how to iterate over the digits, i know how to do it. I'm just looking for a more convenient way.

Does this work?

number.to_string().chars()

I don't understand this request because it seems to directly contradict the question.

You didn't write your way, so I can't know whether it's less convenient.

5 Likes

Many thanks for trying to help me, but it wasn’t my question. First of all, allocating a string just to iterate over digits is a little bit expensive, isn’t it?

Oh, I did it in the same way, and I really don’t like it.

n.to_string()
  .bytes()
  .map(|i| i - 48)

That's not something that can be concluded up-front, and doing it this way can be quite valid.
For example, in my tempus_fugit crate I use exactly this pattern to iterate over the digits of a base-n number, and it's never been too expensive yet.

There is an alternative way though, and that is to repeatedly divide an int value by 10 and use the answer as the next digit; the remainder would be used for the rest of the digits.
That's not specific to Rust though, it can be applied pretty much anywhere.
The reason I employ it in tempus_fugit is to avoid some gnarly base-shifting math.

I don't know, you'd have to profile it.

If you want to avoid heap allocation, perhaps using the smartstring crate will help, it inlines small strings without a heap allocation.

This may not necessarily be the fastest way to do base conversion. This does O(log n) divisions, there are ways to do base conversions using only O(log log n) operations using smarter algorithms. That is counter-intuitive because the output has O(log n) bytes, but note that the input also has O(log n) bytes, and we can do arithmetic operations on the whole input at once. This may matter especially for 64-bit or 128-bit types.

I don't know whether the standard library base conversion in Display is well optimized.

I never claimed it was, merely that it's a possible alternative to using an iterator.

Right, I wasn't criticizing it, just pointing it out because I think OP is hinting that implementing the iterator in a way that computes one digit at a time would be more efficient than bulk-converting the whole number at once to a string, which is not necessarily true.

1 Like

The radixal crate might be what you're looking for. There's also the digits_iterator crate.

2 Likes