add one

o2sh

o2sh

Posted on November 6, 2018

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 minimum rustc 1.26 Travis status

Returns n + 1.

Usage

Add this to your Cargo.toml:

[dependencies]
add-one = "1.0.0"
Enter fullscreen mode Exit fullscreen mode

and this to your crate root:

extern crate add_one;
Enter fullscreen mode Exit fullscreen mode

Example

extern crate add_one;
use add_one::add_one;

use std::str;

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

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

or

$ cargo run 12
$ 13
Enter fullscreen mode Exit fullscreen mode

Thanks

License

Licensed under

Compatibility

The add-one crate is tested for rustc 1.26 and greater.




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 ! :)

💖 💪 🙅 🚩
o2sh
o2sh

Posted on November 6, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

add one
rust add one

November 6, 2018