NeetCode #895LC-1134EasyMath & GeometryNC Algo100
← Back to All Problems#895 · #1134 · Armstrong Number(阿姆斯特朗数)
📌 Problem Statement & Constraints
Given an integer
n, return true if it is an Armstrong number: the sum of each of its digits raised to the power of the number of digits equals n itself. Constraints: 1 <= n <= 10^8.💡 Core Algorithmic Approaches
- Count the number of digits
kofn. - Compute the sum of
d^kover all digitsdofn. - Compare the sum with
n; they are equal exactly for Armstrong numbers. - The exponent is the digit count, not a fixed value, which is the key subtlety.
💻 Benchmark Python3 Implementation
class Solution:
def isArmstrong(self, n: int) -> bool:
digits = [int(d) for d in str(n)]
k = len(digits)
return sum(d ** k for d in digits) == n⚡ Complexity Deep Dive
⏱️ Time Complexity
O(log n): there are O(log n) digits, each raised to a small power.
💾 Space Complexity
O(log n) for the digit list, or O(1) if the digits are processed on the fly.
⚠️ Interview Pitfalls & Follow-ups
- Using a fixed exponent of 3: the exponent is the number of digits, which is not always three (for example
1634is a 4-digit Armstrong number). - Comparing the digit sum with the digit sum of digits: the comparison is against
nitself. - Extracting digits incorrectly: use
% 10and// 10, or convert to a string, but be consistent. - Assuming
dk overflows**: Python integers are unbounded, though in fixed-width languages the bound matters.