Armstrong Number
EasyUpdated: Aug 2, 2025
Practice on:
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:
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 <= 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
- Convert the number to a string to get the number of digits
k. - For each digit, raise it to the power
kand sum the results. - Return true if the sum equals the original number, false otherwise.
Code
Java
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;
}
}
Python
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)