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

  1. Count the number of digits k of n.
  2. Compute the sum of d^k over all digits d of n.
  3. Compare the sum with n; they are equal exactly for Armstrong numbers.
  4. 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 1634 is a 4-digit Armstrong number).
  • Comparing the digit sum with the digit sum of digits: the comparison is against n itself.
  • Extracting digits incorrectly: use % 10 and // 10, or convert to a string, but be consistent.
  • Assuming d k overflows**: Python integers are unbounded, though in fixed-width languages the bound matters.