/// Returns the N-th digit of a number counting from the left.
///
/// Examples:
/// - get_nth_digit_from_left(12345, 1) -> 1
/// - get_nth_digit_from_left(12745, 3) -> 7
fn get_nth_digit_from_left(input_number: i64, digit_position: usize) -> Result<u8, String> {
let digit_string = input_number.abs().to_string();
if digit_position == 0 || digit_position > digit_string.len() {
return Err("Digit position is out of range.".to_string());
}
let digit = digit_string
.chars()
.nth(digit_position - 1)
.unwrap()
.to_digit(10)
.unwrap() as u8;
Ok(digit)
}
fn main() {
let account_number = 987654321;
let fourth_digit_from_left =
get_nth_digit_from_left(account_number, 4).unwrap();
println!("Fourth digit from left: {}", fourth_digit_from_left);
}
/*
run:
Fourth digit from left: 6
*/