DEV Community

Cover image for add one
o2sh
o2sh

Posted on

add one

Here is a little program I wrote in Rust that allows you to add one to any number

GitHub logo o2sh / add-one

adds one to a number

add-one

crate documentation

Returns n + 1.

Example

use add_one::add_one;

fn main() {
    let mut bytes = Vec::new();

    match add_one("123".as_bytes(), &mut bytes) {
        Ok(()) => println!("{}", std::str::from_utf8(&bytes).unwrap()),
        Err(e) => {
            eprintln!("Error: {}", e);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

or

cargo install add-one
add-one 12
13
Enter fullscreen mode Exit fullscreen mode



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)

Collapse
 
o2sh profile image
o2sh

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...

Collapse
 
vberlier profile image
Valentin Berlier

Right so your entire function would run faster than what effectively compiles to a single CPU instruction... 🤔

Collapse
 
nektro profile image
Meghan (she/her)