How to convert this number to a numeric vec?
number = 1234
Expect:
array: Vec<i32> = [1, 2, 3, 4]
How to convert this number to a numeric vec?
number = 1234
Expect:
array: Vec<i32> = [1, 2, 3, 4]
I don't think there is a Rust-specific shortcut for this. Instead you'll have to implement it using your favorite algorithm. One example could be something like this (Rust Playground):
fn number_to_vec(n: i32) -> Vec<i32> {
let mut digits = Vec::new();
let mut n = n;
while n > 9 {
digits.push(n % 10);
n = n / 10;
}
digits.push(n);
digits.reverse();
digits
}
A different way would be to format the number as a string and then split that string into individual digits.
And that is:
fn number_to_vec(n: u32) -> Vec<u32> {
n.to_string()
.chars()
.map(|c| c.to_digit(10).unwrap())
.collect()
}
It looks neaty. If performance doesn't matter