… but that’s exactly how conversion to string works, so handrolling an algorithm would likely be around the same speed.
I don’t know enough about the question, but it’s possible that the interviewer wanted to test this specifically. I’ve had interview questions which were literally “implement itoa.”
In this case where itoa was part of a larger question, if I was conducting the interview I would let you convert to string for now so you could continue, but I would let you know that I wanted to revisit the digit conversion later.
https://github.com/lattera/glibc/blob/master/stdio-common/_i...
It's all bit-shifts, bit-masks and a lot of other hacks to get the maximum performance out of the system you're compiling the code on.
Could I write something with better performance on my system? Yeah, after a week to run tests and write esoteric macros.
pub fn divmod10(x: u32) -> (u32, u32) {
(x / 10, x % 10)
}
generates mov ecx, edi
mov eax, 3435973837
imul rax, rcx
shr rax, 35
lea ecx, [rax + rax]
lea ecx, [rcx + 4\*rcx]
sub edi, ecx
mov edx, edi
retUsing a decimal expansion adds 25% overhead from pure maths. Your cache will be larger if you're working in base ten regardless of what optimizations your compiler does.