Coding problem · Easy · Basics

Armstrong Number

Easy Algorithms & data structures

An Armstrong number (narcissistic number) equals the sum of its digits, each raised to the power of the number of digits. 153 = 1³ + 5³ + 3³. Return true if n (non-negative) is one.

Example 1

Input: n = 153
Output: true

Example 2

Input: n = 123
Output: false

Example 3

Input: n = 9474
Output: true
Explanation: 9⁴ + 4⁴ + 7⁴ + 4⁴ = 9474

Hints

Hint 1

Count the digits first (the length of the number as a string).

Hint 2

Add up digit^count for every digit and compare with n.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(digits) · Space O(1)

Get the digits, let k be how many there are, sum d ** k, and compare with the original number.

Reference solution

function isArmstrong(n) {
  const digits = String(n).split('').map(Number);
  return digits.reduce((sum, d) => sum + d ** digits.length, 0) === n;
}

Was this page helpful?