Armstrong Number
Basic Math
๐ Problem Statement
A number is an Armstrong number (narcissistic number) if it equals the sum of its own digits each raised to the power of the number of digits. For example, . Write a function that returns True if a number is an Armstrong number.
๐ก Intuition
For a number with digits, it is Armstrong if where are its digits. The key insight is that you need the total digit count before summing โ compute it once, then extract each digit using the modulo loop from Day 1.
๐ง Approach
- Count the number of digits:
d = len(str(n))or using . - Extract digits one by one using
n % 10andn // 10. - For each digit, raise it to the power
dand add to a running sum. - Compare the sum to the original number.
โก Complexity Analysis
Time
โ proportional to the number of digits
Space
โ only integer variables
โ ๏ธ Common Mistakes
- Computing the number of digits inside the loop (recalculated wrongly as digits are removed)
- Using
n % 10after modifyingnwithout saving the original โ always saveoriginal = n - Only testing single-digit numbers (1โ9 are trivially Armstrong); test 153, 370, 371, 407
๐ฏ Final Thoughts
Armstrong numbers combine two patterns you've already seen: digit extraction (Day 1, Day 2) and exponentiation. The important lesson here is to compute num_digits once before the loop, not inside it.