Last active
June 14, 2018 21:22
-
-
Save devtanc/842e05878e0db354b642d7e6cb1b4e50 to your computer and use it in GitHub Desktop.
Sums digits of a given i32
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
let args: Vec<String> = std::env::args().collect(); | |
let input = match args[1].parse::<i32>() { | |
Ok(num) => num, | |
Err(error) => panic!("The number provided is too large for an i32: {:?}", error) | |
}; | |
println!("The sum of all digits is {}", sum_digits(&input)); | |
} | |
fn sum_digits(num: &i32) -> i32 { | |
let mut digit_sum = 0; | |
let mut running_num = *num; | |
while running_num != 0 { | |
digit_sum += running_num % 10; | |
running_num /= 10; | |
} | |
digit_sum | |
} | |
#[test] | |
fn check_digit_sum() { | |
assert_eq!(10, sum_digits(&1234)); | |
assert_eq!(15, sum_digits(&12345)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment