DEV Community

Discussion on: Daily Challenge #119 - Adding Big Numbers

Collapse
 
idanarye profile image
Idan Arye

Rust:

fn add(num1: &str, num2: &str) -> Result<String, String> {
    const ZERO_CHAR: u8 = '0' as u8;
    let mut reversed_result = Vec::<u8>::new();
    let max_digits = num1.len().max(num2.len());

    macro_rules! convert_num {
        ($num:expr) => {
            $num.chars().rev().chain(['0'].iter().cloned().cycle())
        }
    }

    let digits1 = convert_num!(num1);
    let digits2 = convert_num!(num2);

    let mut carry = 0;
    for (digit1, digit2) in digits1.zip(digits2).take(max_digits) {
        fn digit_to_numeric(digit: char) -> Result<u8, String> {
            if '0' <= digit && digit <= '9' {
                Ok(digit as u8 - ZERO_CHAR)
            } else {
                Err(format!("{:?} is not a digit", digit))
            }
        }

        let digit1 = digit_to_numeric(digit1)?;
        let digit2 = digit_to_numeric(digit2)?;

        let digit_sum = digit1 + digit2 + carry;
        carry = digit_sum / 10;
        assert!(carry < 10);
        reversed_result.push(digit_sum % 10 + ZERO_CHAR);
    }
    if 0 < carry {
        reversed_result.push(carry + ZERO_CHAR);
    }
    reversed_result.reverse();
    Ok(String::from_utf8(reversed_result).expect("We only added digits"))
}