Problem
Given an integer n
, return true
if and only if it is anArmstrong number.
The k
-digit number n
is an Armstrong number if and only if the kth
power of each digit sums to n
.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
1 <= n <= 10^8
Solution
Method 1 – Check Each Digit and Sum Powers
Intuition
An Armstrong number is a number that is equal to the sum of its own digits each raised to the power of the number of digits. We can extract each digit, raise it to the appropriate power, sum them, and compare to the original number.
Approach
- Convert the number to a string to get the number of digits
k
. - For each digit, raise it to the power
k
and sum the results. - Return true if the sum equals the original number, false otherwise.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(log n)
(number of digits in n) - 🧺 Space complexity:
O(1)