-
-
Notifications
You must be signed in to change notification settings - Fork 50.4k
Expand file tree
/
Copy pathis_armstrong_number.py
More file actions
38 lines (32 loc) · 1.04 KB
/
is_armstrong_number.py
File metadata and controls
38 lines (32 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
def is_armstrong_number(number: int) -> bool:
"""
Check whether a non-negative integer is an Armstrong (narcissistic) number.
An Armstrong number is a number that is the sum of its own digits each raised
to the power of the number of digits in the number.
Reference:
Narcissistic number (Armstrong number) — Wikipedia
https://en.wikipedia.org/wiki/Narcissistic_number
>>> is_armstrong_number(0)
True
>>> is_armstrong_number(1)
True
>>> is_armstrong_number(153)
True
>>> is_armstrong_number(370)
True
>>> is_armstrong_number(9474)
True
>>> is_armstrong_number(9475)
False
>>> is_armstrong_number(-1) # negative numbers are not considered Armstrong
False
"""
# Only non-negative integers are considered
if number < 0:
return False
# Convert to string to count digits
digits = str(number)
power = len(digits)
# Sum of each digit raised to the 'power'
total = sum(int(d) ** power for d in digits)
return total == number