我试图找到一个给定数字的数字之和.例如,134
等于8
.
我的计划是使用.to_string()
将数字转换为字符串,然后使用.chars()
将数字作为字符进行迭代.然后,我想将迭代中的每char
个变量转换成一个整数,并将其添加到一个变量中.我想得到这个变量的最终值.
我try 使用下面的代码将char
转换为整数:
fn main() {
let x = "123";
for y in x.chars() {
let z = y.parse::<i32>().unwrap();
println!("{}", z + 1);
}
}
但它会导致这个错误:
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();
| ^^^^^
这段代码正是我想做的,但首先我必须将每个char
转换成一个字符串,然后转换成一个整数,然后将sum
乘以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);
}