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 the number into a string using .to_string()
and then use .chars()
to iterate over the digits as characters. Then I want to convert every char
in the iteration into 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 a char
into an integer:
fn main() {
let x = "123";
for y in x.chars() {
let z = y.parse::<i32>().unwrap();
println!("{}", z + 1);
}
}
But it results in 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 to do, but first I have to convert each char
into a string and then into an integer to 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);
}