Armstrong Number
Easy · Math & Geometry · Explanation and code example
Calculate k Without Built-in Methods
How it works
We can count digits without any built-in functions by simply dividing the number by 10 until it becomes 0, counting iterations. This approach uses only basic arithmetic and works in any language without library dependencies.
Steps
- Copy
nto a temporary variable. - Count digits by dividing by 10 until the number becomes 0.
- Extract each digit from the original number and sum
digit^k. - Return
trueif the sum equalsn.
Complexity
-
Time complexity:
O(M) -
Space complexity:
O(1)constant space
Where
Mis the number of digits in the input integern.
Things to watch for
Using a Fixed Power Instead of the Digit Count
A common mistake is hardcoding the exponent (e.g., always using 3) instead of dynamically calculating the number of digits. Armstrong numbers are defined with respect to their digit count, so 153 uses power 3, but 1634 uses power 4.
Modifying the Original Number Without Saving It
When extracting digits by repeatedly dividing by 10, the original number gets destroyed. Forgetting to save the original value before the loop means you have nothing to compare the sum against.
Python code example
class Solution:
def isArmstrong(self, n: int) -> bool:
def getSumOfKthPowerOfDigits(num, k):
result = 0
while num != 0:
result += (num % 10) ** k
num //= 10
return result
length = 0
temp_n = n
while temp_n != 0:
length += 1
temp_n //= 10
return getSumOfKthPowerOfDigits(n, length) == n
C++ code example
class Solution {
public:
int getSumOfKthPowerOfDigits(int n, int k) {
int result = 0;
while(n != 0) {
result += pow(n % 10, k);
n /= 10;
}
return result;
}
bool isArmstrong(int n) {
int length = 0;
int tempN = n;
while (tempN) {
length++;
tempN /= 10;
}
return getSumOfKthPowerOfDigits(n, length) == n;
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.