Here is a little program I wrote in Rust that allows you to add one to any number
The idea is pretty simple. Indeed, since incrementing a number leaves most of it unchanged, it's much faster to work on the decimal digits itself.
As a consequence, after breaking the input into a list of digits, we just have to increment or decrement (in case of negative input) the last number.
Not so fast...
What if the number has trailing nines for positive inputs or trailing zeros for negative numbers ?
Well, if the number has trailing nines (e.g.: 7561325999) or trailing zeros (e.g.: -1645000), we just need to increment the last "non-nine" digit (or decrement the last "non-zero" digit) and switch the nines into zeros and zeros into nines (for negative inputs).
And, in the case of floating point inputs (e.g.: 15691.12313) we simply ignore the decimal part and apply the previous rule to the integer part.
Unless...
...the input belongs to ]-1,0[ (e.g.: -0.2 + 1 = 0,8 (not 1.2!)). In which case, we have to give it a special treatment.
Thanks for reading ! :)
Top comments (4)
It's a different approach without the limitations. Indeed, the input is not bound to a type (i32, i64...) and can be very big.
It may also be faster...
Right so your entire function would run faster than what effectively compiles to a single CPU instruction... 🤔
github.com/sindresorhus/ama/issues...