The Self-Portrait Number

An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
easy
Seniority
L3
Asked in
Citadel

Problem

Given a positive integer n with d digits, return True if the sum of each digit raised to the power d equals n. (Armstrong / narcissistic number check.)

Some numbers describe themselves perfectly.

Example 1

Input:

n = 153

Output:

true

Example 2

Input:

n = 123

Output:

false

Worked solution and explanation

Why this problem exists in real interviews

This probes digit extraction, exponentiation, and basic loop mechanics. It is a straightforward math problem that reveals whether a candidate can decompose an integer into its digits and apply an operation to each one cleanly.


Break down the requirements

Step 1: Count the total number of digits

Convert the number to a string to get the digit count, or use repeated division. The exponent depends on this count.

Step 2: Extract each digit and raise it to the power of the digit count

Iterate through each digit, compute digit ** num_digits, and accumulate the sum.

Step 3: Compare the sum to the original number

If the accumulated sum equals the input, return True.


The solution

Digit extraction with exponentiation
def is_armstrong(n: int) -> bool:
    digits = str(n)
    num_digits = len(digits)
    total = 0
    for d in digits:
        total += int(d) ** num_digits
    result = total == n
    return result

Common follow-up questions