An Armstrong number equals the sum of its digits each raised to the power of the total digit count. For example, 153 has 3 digits, and 1^3 + 5^3 + 3^3 = 153.
The straightforward approach is to convert the number to a string to count digits, then extract each digit and compute the sum of powers. We compare this sum to the original number.
n to a string and get its length k.n % 10 and dividing by 10.digit^k to a running sum.true if the sum equals the original number.Time complexity:
Space complexity: constant space
Where is the number of digits in the input integer
n.
Instead of converting to a string, we can use logarithms to count digits. The number of digits in a positive integer n is floor(log10(n)) + 1. This avoids string allocation and can be slightly more efficient.
The rest of the logic remains the same: extract digits, raise each to the power of k, sum them up, and compare.
k = floor(log10(n)) + 1 to get the digit count.k.true if the sum equals n.Time complexity:
Space complexity: constant space
Where is the number of digits in the input integer
n.
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.
n to a temporary variable.digit^k.true if the sum equals n.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) == nTime complexity:
Space complexity: constant space
Where is the number of digits in the input integer
n.
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.
# Wrong: always using power 3
result += digit ** 3When 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.
# Wrong: n is modified and can't be compared later
while n != 0:
result += (n % 10) ** k
n //= 10
return result == n # n is now 0!