1134. Armstrong Number

Given an integer n, return true if and only if it is an Armstrong number.

The k-digit number n is an Armstrong number if and only if the kth power of each digit sums to n.

 

Example 1:

Input: n = 153
Output: true
Explanation: 153 is a 3-digit number, and 153 = 13 + 53 + 33.

Example 2:

Input: n = 123
Output: false
Explanation: 123 is a 3-digit number, and 123 != 13 + 23 + 33 = 36.

 

Constraints:

  • 1 <= n <= 108

Rust Solution

struct Solution;

impl Solution {
    fn is_armstrong(n: i32) -> bool {
        let mut x = n;
        let mut k = 0;
        let mut digits: Vec<i32> = vec![];
        while x > 0 {
            let d = x % 10;
            digits.push(d);
            x /= 10;
            k += 1;
        }
        let sum: i32 = digits.iter().map(|x| x.pow(k)).sum();
        sum == n
    }
}

#[test]
fn test() {
    assert_eq!(Solution::is_armstrong(153), true);
    assert_eq!(Solution::is_armstrong(123), false);
}

Having problems with this solution? Click here to submit an issue on github.