220. ilog10 — Count an Integer's Digits Without Formatting It to a String
Need to know how many digits a number has? Reaching for n.to_string().len() allocates a whole String just to measure it. ilog10 answers the same question with one instruction and zero allocation.
The classic way to count digits builds a string and throws it away:
| |
ilog10 returns the floor of the base-10 logarithm, so the digit count is just that plus one — no allocation, no formatting:
| |
The one catch: 0 has no logarithm, so 0u32.ilog10() panics. Guard the zero case, since “0” still has one digit:
| |
Prefer no branch? checked_ilog10 returns None for zero instead of panicking, so you can fold the special case into one expression:
| |
There’s also ilog2 when you want a power-of-two magnitude — the index of the highest set bit:
| |
All three (ilog10, ilog2, checked_ilog10) work on every integer type. Skip the string round-trip — the math is right there.