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

  1. Copy n to a temporary variable.
  2. Count digits by dividing by 10 until the number becomes 0.
  3. Extract each digit from the original number and sum digit^k.
  4. Return true if the sum equals n.

Complexity

  • Time complexity: O(M)

  • Space complexity: O(1) constant space

Where M is the number of digits in the input integer n.

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.

Your recall check is in progress. Write your attempt before revealing the explanation.

Resume recall check

Browse all problem explanations