Easy 0 solved 0% acceptance

Armstrong Number

Check whether a number equals the sum of its digits raised to the digit count.

What you'll learn

  • Count the digits of a number
  • Raise each digit to the digit count and add them up
  • Compare the result with the original number

Problem

A number with k digits is an Armstrong number if the sum of each digit raised to the power k equals the number. For example 153 = 1³ + 5³ + 3³.

Implement is_armstrong(n).

Input

n: A non-negative integer.

Output

Return true if n is an Armstrong number.

Constraints

0 ≤ n ≤ 10¹⁸

Examples

Example 1
Input:
n = 153

Expected output:
expected = True
Input:
long long n = 153;

Expected output:
bool expected = true;
Input:
long n = 153;

Expected output:
bool expected = true;

Explanation

1³ + 5³ + 3³ = 1 + 125 + 27 = 153.

Example 2
Input:
n = 10

Expected output:
expected = False
Input:
long long n = 10;

Expected output:
bool expected = false;
Input:
long n = 10;

Expected output:
bool expected = false;

Explanation

1² + 0² = 1, which is not 10.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Count how many digits the number has before summing powers.

Hint 2

Compare the original number with the sum of each digit raised to that digit count.

Hint 3

Remember that 0 is a special one-digit case.

Expected complexity

O(k) time, O(1) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.