Hi, I would like some advice about my code for solving the Armstrong Numbers exercise.
The problem is quite simple, Armstrong Numbers are numbers equal to the sum the digits to the power of the length. For example: 153 == 1^3 + 5^3 + 3^3. Here the length is 3. (They consider decimal system only.)
Is there an option that is obviously better in the two cases below?
you can save the allocation and string conversion even tho it's a bit less elegant looking
//! A power number such as:
//! 153 = 1^3 + 5 ^3 + 3^3 = 153
//! i.e. sum each digit elevated to the power of its length.
// Base 10 only at the moment.
pub fn is_armstrong_number(num: u32) -> bool {
let lenght = num.checked_ilog10().unwrap_or(0) + 1
let mut remaining_digits=num;
let mut remaining_total=num;
for i in 0..lenght{
let digit=remaining_digits%10;
remaining_digits=remaining_digits/10;
let power=digit.pow(lenght);
if power>remaining_total{
return false;
}
remaining_total-=power;
}
return true;
}
I've refactored using a mix of both suggestions. It may still be non-optimal.
pub fn is_armstrong_number(num: u32) -> bool {
if num == 0 {
return true;
}
let l = num.ilog10() + 1; // length
let mut d = 0; // The current digit
let mut num_upd = num; // Update number elsewhere.
let result: Option<u32> = (0..l).try_fold(0u32, |acc, _| {
d = num_upd % 10;
num_upd /= 10;
acc.checked_add(d.pow(l))
});
result == Some(num)
}
PS: I think the function signature given by the exercise should return Result<bool, String> or Option<bool>.
I wonder whether others would agree. Maybe not for this exercise but in other cases.