I am trying to find the sum of the digits of a given number. For example, 134 will give 8 .
My plan is to convert a number to a string using .to_string() and then use .chars() to iterate over the numbers as characters. Then I want to convert each char in iteration to an integer and add it to a variable. I want to get the final value of this variable.
I tried using the code below to convert char to an integer:
fn main() { let x = "123"; for y in x.chars() { let z = y.parse::<i32>().unwrap(); println!("{}", z + 1); } }
( Playground )
But this leads to this error:
error[E0599]: no method named 'parse' found for type 'char' in the current scope --> src/main.rs:4:19 | 4 | let z = y.parse::<i32>().unwrap(); | ^^^^^
This code does exactly what I want, but first I have to convert each char to a string, and then to an integer, and then increment sum by z .
fn main() { let mut sum = 0; let x = 123; let x = x.to_string(); for y in x.chars() { // converting 'y' to string and then to integer let z = (y.to_string()).parse::<i32>().unwrap(); // incrementing 'sum' by 'z' sum += z; } println!("{}", sum); }
( Playground )
source share