Problem

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

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

Examples

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= n <= 10^8

Solution

Method 1 – Check Each Digit and Sum Powers

Intuition

An Armstrong number is a number that is equal to the sum of its own digits each raised to the power of the number of digits. We can extract each digit, raise it to the appropriate power, sum them, and compare to the original number.

Approach

  1. Convert the number to a string to get the number of digits k.
  2. For each digit, raise it to the power k and sum the results.
  3. Return true if the sum equals the original number, false otherwise.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
    public boolean isArmstrong(int n) {
        int k = Integer.toString(n).length();
        int sum = 0, x = n;
        while (x > 0) {
            int d = x % 10;
            sum += Math.pow(d, k);
            x /= 10;
        }
        return sum == n;
    }
}
1
2
3
4
class Solution:
    def isArmstrong(self, n: int) -> bool:
        k = len(str(n))
        return n == sum(int(d) ** k for d in str(n))

Complexity

  • ⏰ Time complexity: O(log n) (number of digits in n)
  • 🧺 Space complexity: O(1)