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;
}
function isArmstrong(n: number): boolean {
const digits = String(n).split('').map(Number);
return digits.reduce((sum, d) => sum + d ** digits.length, 0) === n;
}
def is_armstrong(n: int) -> bool:
digits = [int(ch) for ch in str(n)]
return sum(d ** len(digits) for d in digits) == n
<?php
function isArmstrong(int $n): bool
{
$digits = str_split((string) $n);
$k = count($digits);
return array_sum(array_map(fn ($d) => ((int) $d) ** $k, $digits)) === $n;
}
class Solution {
public boolean isArmstrong(int n) {
String s = String.valueOf(n);
long sum = 0;
for (char ch : s.toCharArray()) sum += (long) Math.pow(ch - '0', s.length());
return sum == n;
}
}
More Basics problems
- Reverse a String · Easy
- Count the Vowels · Easy
- Capitalize Each Word · Easy
- Longest Word in a Sentence · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy