We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Armstrong Number

Number: 1090

Difficulty: Easy

Paid? Yes

Companies: Amazon


Problem Description

Write a function that takes an integer n and returns true if and only if n is an Armstrong number. An Armstrong number is defined such that for a k-digit number, the sum of each digit raised to the power k equals n.


Key Insights

  • Determine the number of digits (k) in the number.
  • Extract each digit and raise it to the power of k.
  • Sum these computed values.
  • Compare the resulting sum with the original number to decide if it's an Armstrong number.

Space and Time Complexity

Time Complexity: O(d), where d is the number of digits (at most 9 for n <= 10^8).
Space Complexity: O(1)


Solution

The solution involves converting the integer into a string (or processing its digits numerically) to determine the number of digits. For each digit, compute the k-th power and sum these values. Finally, compare the sum to the original number. This method leverages simple arithmetic operations and basic string manipulation to effectively determine if the number qualifies as an Armstrong number.


Code Solutions

# Function to check if the given number is an Armstrong number.
def is_armstrong(n):
    # Convert the number to a string to get the count of digits.
    num_str = str(n)
    k = len(num_str)
    # Sum each digit raised to the power k.
    total = sum(int(digit) ** k for digit in num_str)
    # Return True if the sum equals n, False otherwise.
    return total == n

# Test examples
print(is_armstrong(153))  # Expected output: True
print(is_armstrong(123))  # Expected output: False
← Back to All Questions